Mastering unix shell scripting phần 10 docx

73 347 0
Mastering unix shell scripting phần 10 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

RESULT=”2#1101101011” The next step is to typeset the BASE_TO variable to the target number base. This is also accomplished using the previously defined variable END_BASE, as shown here. typeset -i$END_BASE RESULT Now let’s assume that the target number base, $END_BASE, is 16. The following command statement is equivalent to the preceding variable statement. typeset -i16 RESULT The only thing left to do is print the result to the screen. You can use echo, print, or printf to display the result. I still like to use echo, so this is the final line of the shell script. echo $RESULT Other Options to Consider As with all of the scripts in this book, we can always make some changes to any shell script to improve it or to customize the script to fit a particular need. Software Key Shell Script To make a software key more complicated you can hide the hexadecimal representa- tion of the IP address within some pseudo-random numbers, which we studied in Chapters 10 and 21. As an example, add five computer-generated pseudo-random numbers as both a prefix and a suffix to the hexadecimal IP address representation. Then to verify the license key in your software program you can extract the hex IP address from the string. There are several techniques to do this verification, and I am going to leave the details up to you as a little project. This is the only modification that I can think of for this chapter. Summary We went through a lot of variations in this chapter, but we did hit the scripts from different angles. Number base conversion can be used for many purposes, and we wrote one script that takes advantage of the translation. Software keys are usually more complicated than this script example, but I think you get the basic idea. In the next chapter we are going to look at creating a menu that is suitable for your operations staff because you rarely want the Operators to have access to the command line. See you in the next chapter! 608 Chapter 23 609 Oh yes, we can never forget about the Operations staff! A lot of us traveled along this road in the beginning; I know I did back in the 1980s. These guys still do the grunt work, but most of the time you do not want a beginning Operator to get near a com- mand prompt for everyday tasks. The chance for small mistakes is too great with the newcomers, but we must give them the ability to do their job. This ability is easily given to the Operators by a menu that has all of the functionality that they need to get the job done, and we might as well make it a nice-looking menu. Some of the more common operations tasks include managing the print queues, man- aging the backup tapes, and changing user passwords. There are many more tasks, but this short list will get us started. First, let’s set some expectations. Normally, this type of shell script is put in the user’s $HOME/.profile or other login configuration file, and when the user logs in the menu is presented. When the user exits the menu the user is logged out immedi- ately. Using this method we do our best not to let the user gain access to a command prompt. Be careful! If a program like vi is in the menu, then all a user has to do is escape out to a shell with a couple of key strokes and the user is at a command prompt. Of course, if your Operators can find a way to get a command prompt, then just give it to them! Menu Program Suitable for Operations Staff CHAPTER 24 The techniques used in this chapter involve using reverse video, as we last saw in Chapter 15 when we created the hgrep shell script. This time we will use reverse video in a menu interface, again using the tput command options. Reverse Video Syntax To start off we want to give the menu a reverse video title bar across the top of the screen. To refresh your memory, to turn on reverse video we use tput smso and to turn off the highlight we use tput rmso. For this title bar we will use the system’s hostname in the title. After the script is started we will remain in the menu until 99 (exit) is entered as a menu selection. We also would like to highlight the menu options next to the option label. The title bar is first. clear # Clear the screen first tput smso # Turn on reverse video echo “ $(hostname)\c” # 33 spaces echo “ “ # 39 spaces tput rmso # Turn off reverse video In the preceding code block we first clear the screen for the menu using the clear command. The second line will turn on the reverse video using the tput smso com- mand. An echo statement that executes the Unix command hostname, as command substitution, follows this. In both echo statements the blank spaces are highlighted, which results in a bar across the top of the screen with the system’s hostname in the middle, displayed in reverse video. Notice that before the hostname there are 33 spaces and after the hostname there are 39 more spaces. This allows up to 8 characters for the hostname in the middle of the title bar. You can adjust this spacing easily to suit your needs. Creating the Menu The next thing we want to do is display the menu options. For this step we want to make the selection options appear in reverse video to the left of the option label. We will again use command substitution, but this time to turn on and off the highlight within an echo statement. The block of code shown in Listing 24.1 will handle this nicely. echo “$(tput smso)1$(tput rmso) - Tape Management” echo “$(tput smso)2$(tput rmso) - Initialize New Tapes” echo “$(tput smso)3$(tput rmso) - Dismount Tape Volume” echo “$(tput smso)4$(tput rmso) - Query Volumes in Library” echo “$(tput smso)5$(tput rmso) - Query Tape Volumes” echo “$(tput smso)6$(tput rmso) - Audit Library/Check-in Scratch Volumes” echo “$(tput smso)7$(tput rmso) - Print Tape Volume Audit Report” echo “\n\n” # Print two blank lines Listing 24.1 Reverse video menu options. 610 Chapter 24 echo “$(tput smso)10$(tput rmso) - Change Password” echo “$(tput smso)11$(tput rmso) - Enable all Print Queues echo “\n\n\n\n\n\n” echo “$(tput smso)99$(tput rmso) - Logout\n” Listing 24.1 Reverse video menu options. (continued) Notice how the command substitution works in the echo statements. Highlighting is turned on, the menu selection number is displayed, and reverse video is turned off, then the selection label is printed in plain text. Creating a Message Bar for Feedback Another nice thing to have in our menu is a message bar. This can be used to display a message for an invalid option selection and also can be used to display a message if we want to disable a menu option. For this we want to set the message up to assume an invalid selection, and we will blank the message variable out if we have valid input. In case we want to disable an option in the menu we can comment out the commands that we want to disable and put a disabled option comment in the message variable. The next few lines of code, shown in Listing 24.2, will work to display the message bar. # Draw a reverse video message bar across bottom of screen, # with the error message displayed, if there is a message. tput smso # Turn on reverse video echo “ ${MSG}\c” # 30 spaces echo “ “ # 26 spaces tput rmso # Turn off reverse video # Prompt for menu option. echo “Selection: \c” read OPTION # Assume the selection was invalid. Because a message is always # displayed we need to blank it out when a valid option # is selected. MSG=”Invalid Option Selected.” # 24 spaces Listing 24.2 Setting up the reverse video message bar. Menu Program Suitable for Operations Staff 611 This message bar works the same as the title bar. The text message pointed to by $MSG is displayed in the middle of the message bar. Notice that we are assuming an invalid option was entered as the default. If we have valid input we need to replace the text in the $MSG variable with 24 blank spaces, for a total of 80 characters. This way we have only a highlighted bar, without any text, across the screen. We do this in each option of the case statement that is used to process the menu selections. The entire shell script is shown in Listing 24.3. See how menu option 5 is disabled in the case statement. #!/usr/bin/ksh # # SCRIPT: operations_menu.ksh # AUTHOR: Randy Michael # DATE: 09-06-2001 # REV 2.0.P # # PLATFORM: Any Unix OS, with modifications # # PURPOSE: This script gives the operations staff an easy- # to-follow menu to handle daily tasks, such # as managing the backup tapes and changing # their password # # REV LIST: # # # set -n # Uncomment to check script syntax without any execution # set -x # Uncomment to debug this script # ############################################### ####### DEFINE FILES AND VARIABLES HERE ####### ############################################### BINDIR=”/usr/local/bin” PASSWORD_SERVER=”yogi” THIS_HOST=$(hostname) ############################################### ########## INITIALIZE VARIABLES HERE ########## ############################################### MSG=” “ OPT=” “ # Variable for menu selection ############################################### ############## SET A TRAP HERE ################ Listing 24.3 operations_menu.ksh shell script listing. 612 Chapter 24 ############################################### trap ‘echo “\nEXITING on a TRAPPED SIGNAL\n”; \ exit 1’ 1 2 3 15 ############################################### ############ BEGINNING OF MAIN ################ ############################################### # Loop until option 99 is Selected # We use 99 as a character instead of an integer # in case a user enters a non-integer selection, # which would cause the script to fail. while [[ $OPT != 99 ]] do # Display a reverse video image bar across the top # of the screen with the hostname of the machine. clear # Clear the screen first tput smso # Turn on reverse video echo “ ${THIS_HOST}\c” echo “ “ tput rmso # Turn off reverse video echo “\n” # Add one blank line of output # Show the menu options available to the user with the # numbered options highlighted in reverse video # # $(tput smso) Turns ON reverse video # $(tput rmso) Turns OFF reverse video echo “$(tput smso)1$(tput rmso) - Tape Management” echo “$(tput smso)2$(tput rmso) - Label Tapes” echo “$(tput smso)3$(tput rmso) - Query Volumes in Library” echo “$(tput smso)4$(tput rmso) - Query Tape Volumes” echo “$(tput smso)5$(tput rmso) - Audit/Check-in Scratch Volumes” echo “$(tput smso)6$(tput rmso) - Print Tape Volume Audit Report” echo “\n\n” # Print two new lines echo “$(tput smso)7$(tput rmso) - Change Password” echo “$(tput smso)8$(tput rmso) - Enable all Print Queues” echo “\n\n\n\n” Listing 24.3 operations_menu.ksh shell script listing. (continues) Menu Program Suitable for Operations Staff 613 echo “$(tput smso)99$(tput rmso) - Logout\n” # Draw a reverse video message bar across bottom of screen, # with the error message displayed, if there is a message. tput smso # Turn on reverse video echo “ ${MSG}\c” echo “ “ tput rmso # Turn off reverse video # Prompt for menu option. echo “Selection: \c” read OPT # Assume the selection was invalid. Because a message is always # displayed we need to blank it out when a valid option # is selected. MSG=”Invalid option selected.” # Process the Menu Selection case $OPT in 1) # Option 1 - Tape Management ${BINDIR}/manage_tapes.ksh MSG=” “ ;; 2) # Option 2 - Tape Labeling ${BINDIR}/label_tapes.ksh MSG=” “ ;; 3) # Option 3 - Query Tape Volumes in Library dsmadmc -ID=admin -Password=pass query libvol print “Press ENTER to continue” read MSG=” “ ;; 4) Listing 24.3 operations_menu.ksh shell script listing. 614 Chapter 24 # Option 4 - Query Tape Volumes clear # Clear the screen print “Enter Tape Volume to Query:” read ANSWER dsmadmc -ID=admin -PAssword=pass query vol $ANSWER \ format=detailed if (($? == “11”)) # Check for “Not Found” then print “Tape Volume $ANSWER not found in database.” print “Press ENTER to continue.” read fi MSG=” “ ;; 5) # Option 5 - Audit/Checkin Scratch Volumes # dsmadmc -ID=admin -PAssword=pass audit library mainmount # dsmadmc -ID=admin -PAssword=pass checkin libvol mainmount\ # status=scratch search=yes # Not for Operations anymore!!! MSG=” Option is disabled. “ ;; 6) # Option 6 - Print Tape Volume Audit Report ${BINDIR}/print_audit_report.ksh MSG=” “ ;; 7) # Option 7 - Change Password echo “Remote Shell into $PASSWORD_SERVER for Password Change” echo “Press ENTER to continue: \c” read KEY rsh $PASSWORD_SERVER passwd # ssh $PASSWORD_SERVER passwd MSG=” “ ;; 8) # Option 8 - Enable all print queues echo “Attempting to Enable all print queues \c” ${BINDIR}/enable_all_queues.ksh echo “\nQueue Enable Attempt Complete\n” Listing 24.3 operations_menu.ksh shell script listing. (continues) Menu Program Suitable for Operations Staff 615 sleep 1 MSG=” “ ;; esac # End of Loop until 99 is selected done # Erase menu from screen upon exiting with the “clear” command clear # End of Script Listing 24.3 operations_menu.ksh shell script listing. (continued) From the Top Let’s look at this script from the top. The first step is to define files and variables. In this section we define three variables, our BINDIR directory, which is the location of all of the shell scripts and programs that we call from the menu. The second variable is the hostname of the password server. I use a single server to hold the master password list, and every 15 minutes this master password file is pushed out to all of the other servers in the landscape. This method just makes life much easier when you have a lot of machines to manage. Of course you may use NIS or NIS+ for this functionality. The last variable is the hostname of the machine running the menu, THIS_HOST. Next we initialize two variables; one is for the message bar, and the other is for the menu options, $MSG and $OPT. After initializing these two variables we set a trap. This trap is just informational. All that we want to do if this shell script receives a trapped signal is to let the user know that this program exited on a trapped signal, nothing more. Now comes the fun stuff at the BEGINNING OF MAIN. For the menu we stay in a loop until the user selects 99 as a menu option. Only an exit signal or a 99 user selec- tion will exit this loop. The easiest way to create this loop is to use a while loop speci- fying 99 as the exit criteria. Each time through the loop we first clear the screen. Then we display the title bar, which has the hostname of this machine, specified by the $THIS_HOST variable. Next we display the menu options. This current menu has 8 options, plus the 99 exit selection. We preset the message bar to always assume an incorrect entry. If the entry is valid, then we overwrite the $MSG variable with blank spaces. After the message bar is dis- played we prompt the user for a menu selection. When a valid selection is made we jump down to the case statement, which executes the selected menu option. 616 Chapter 24 Notice that the message string, $MSG, is always the same length, 24 characters. This is a requirement to ensure that the message bar and the title bar are the same length; assuming an eight character hostname. This is also true for the hostname in the title bar. In each of the case statement options we process the menu selection and make the $MSG all blank spaces, with the exception of item number 5. We disabled menu option 5 by commenting out all of the code and changing the $MSG to read Option is Disabled. This is an easy way to remove a menu option from being executed temporarily. The $MSG will always be displayed in the message bar, whether the “message” is all blank spaces or an actual text message. Both the title and message bars are always 80 characters long, assuming a hostname of 8 characters. You may want to add some code to ensure that the title bar is always 80 characters. This is a little project for you to resolve. The 8 menu options include the following: ■■ Tape management ■■ Tape labeling ■■ Query tape volumes in the library ■■ Query tape volumes ■■ Audit/check-in scratch volumes ■■ Print tape volume audit report ■■ Change password ■■ Enable all print queues ■■ 99—exit For each valid menu selection in this script either a local command is executed or an external program or shell script is executed. You will have to modify this menu script to suit your needs. Do not assume that the TSM commands listed as menu options in this script will work without modification. These menu entries are just an example of the types of tasks that you may want your operations staff to handle. Every environ- ment is different and some operations staff members are more capable than others. For safety I recommend that you add this shell script name to the end of the users’ $HOME/.profile and follow this script name with the exit command as the last entry in the user’s .profile. This method allows the Operators to log in to run the tasks in the menu. When 99 is selected the menu is exited and the user is logged out of the sys- tem due to the exit command, without ever seeing a command prompt. Other Options to Consider This script, like any other shell script, can be improved. I can think of only a couple of things that I might add depending on the environment. You may have better ideas on how a menu should look and work, but this is one way to get the job done in an easily readable script. Menu Program Suitable for Operations Staff 617 [...]... interface Connected Type sent 13 bytes added interface ip =10. 10 .10. 1 bcast =10. 10.255.255 nmask=255.255.0.0 your message, ending it with a Control-D ip =10. 10 .10. 1 bcast =10. 10.255.255 nmask=255.255.0.0 your message, ending it with a Control-D ip =10. 10 .10. 1 bcast =10. 10.255.255 nmask=255.255.0.0 your message, ending it with a Control-D ip =10. 10 .10. 1 bcast =10. 10.255.255 nmask=255.255.0.0 643 ... ############################################################ # Define the file directory for this shell script GRP_DIR=”/usr/local/bin” # Define all valid groups to send messages GROUPLIST= UNIX SAP ORACLE DBA APPA APPB” # Define all of the Group files UNIX= ”${GRP_DIR}/Unixlist” SAP=”${GRP_DIR}/SAPlist” Listing 25.9 broadcast.ksh shell script listing Sending Pop-Up Messages from Unix to Windows ORACLE=”${GRP_DIR}/ORACLElist” DBA=”${GRP_DIR}/DBAlist”... Sending message to the following hosts: WIN_HOSTS: booboo Sending the Message Sending to ==> booboo added interface ip =10. 10 .10. 1 bcast =10. 10.255.255 nmask=255.255.0.0 Connected Type your message, ending it with a Control-D sent 45 bytes Sent OK ==> booboo Listing 25.11 broadcast.ksh shell script in action My booboo machine is an NT 4 box The pop-up message that I received is shown in Figure 25.1 The... variable definitions section of this shell script # # You also have the ability of setting up individual GROUPS of # users/nodes by defining the group name to the GROUPLIST variable # Then define the filename of the group For example, to define a # Unix and DBA group the following entries need to be made in this # shell script: # # GROUPLIST= UNIX DBA” # UNIX= ”/scripts/UNIXlist” # DBA=”/scripts/DBAlist”... segment is commented out by default # # Send the message to the Unix machines too using “wall” # and “rwall” if you desire to do so This code is commented # out by default # # echo “\nSending Message to the Unix machines \n” # # echo $MESSAGE | rwall -h $UnixHOSTLIST Listing 25.9 broadcast.ksh shell script listing Sending Pop-Up Messages from Unix to Windows # echo $MESSAGE | wall # echo “\n\nMessage sent... Together Now that we have covered most of the individual pieces that make up the broadcast.ksh shell script, let’s look at the whole shell script and see how the pieces fit together The entire shell script is shown in Listing 25.9 Please pay particular attention to the boldface text Sending Pop-Up Messages from Unix to Windows #!/bin/ksh # # SCRIPT: broadcast.ksh # AUTHOR: Randy Michael # Systems Administrator... have the following list of individual groups: Unix, DBA, ORACLE, DB2, APPLICATION, and so on Then we have a default list of ALL Windows machines in the business, or at least in a department With all of these options in mind I started rewriting an already working shell script In the next sections we are going to put the pieces together and make a very flexible shell script that you can tailor to suit your...618 Chapter 24 Shelling Out to the Command Line Be extremely careful about the commands that you put into the menu Some programs are very easy to get to a shell prompt The example I mentioned earlier was the vi editor With a couple of key strokes you can suspend vi and get to a shell prompt You can do this with many other programs, too Good Candidate... elif [ ! -x $SMBCLIENT ] then Listing 25 .10 check_for_smbclient_command function listing (continues) 639 640 Chapter 25 echo “\nERROR: $SMBCLIENT command is not executable\n” echo “Please correct this problem and try again\n” exit 4 fi } Listing 25 .10 check_for_smbclient_command function listing (continued) Notice that we use the which command in Listing 25 .10 to find the smbclient command in the $PATH... Messages from Unix to Windows There is a need in every shop for quick communications to the users in your environment Getting a message out quickly when an application has failed is a good example In this chapter we are going to look at a method of sending “pop-up” messages to Windows desktops The only requirement for the Unix machines is that Samba must be configured and running on the Unix sever Samba . RESULT=”2# 1101 1 0101 1” The next step is to typeset the BASE_TO variable to the target number base. This is also. this is the final line of the shell script. echo $RESULT Other Options to Consider As with all of the scripts in this book, we can always make some changes to any shell script to improve it or. need. Software Key Shell Script To make a software key more complicated you can hide the hexadecimal representa- tion of the IP address within some pseudo-random numbers, which we studied in Chapters 10 and

Ngày đăng: 09/08/2014, 16:20

Từ khóa liên quan

Mục lục

  • Chapter 23 Scripts for Number Base Conversions

    • Other Options to Consider

      • Software Key Shell Script

      • Summary

      • Chapter 24 Menu Program Suitable for Operations Staff

        • Reverse Video Syntax

          • Creating the Menu

            • Creating a Message Bar for Feedback

            • From the Top

            • Other Options to Consider

              • Shelling Out to the Command Line

              • Good Candidate for Using sudo

              • Summary

              • Chapter 25 Sending Pop-Up Messages from Unix to Windows

                • About Samba and the smbclient Command

                • Syntax

                • Building the broadcast.ksh Shell Script

                  • Sending a Message to All Users

                  • Adding Groups to the Basic Code

                  • Adding the Ability to Specify Destinations Individually

                    • Using getopts to Parse the Command Line

                    • Testing User Input

                      • Testing and Prompting for WINLIST Data

                      • Testing and Prompting for Message Data

                      • Sending the Message

                      • Putting It All Together

                        • Watching the broadcast.ksh Script in Action

                        • Downloading and Installing Samba

                          • Testing the smbclient Program the First Time

                          • Other Options to Consider

                            • Producing Error Notifications

                            • Add Logging of Unreachable Machines

                            • Create Two-Way Messanging

Tài liệu cùng người dùng

Tài liệu liên quan