1. Trang chủ
  2. » Công Nghệ Thông Tin

Mastering Unix Shell Scripting phần 5 doc

71 237 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 71
Dung lượng 452,23 KB

Nội dung

Application APIs and SNMP Traps Most enterprise management tools come with application program interfaces (APIs) for the more common commercial applications; however, we sometimes must write shell scripts to fill in the gaps. This is where SNMP traps come in. Because the enter- prise management tool should support SNMP traps, the APIs allow the application to be monitored using the SNMP MIB definitions on both the management server and the client system. When an enterprise management tool supports SNMP traps, you can usually write your own shell scripts that can use the tool’s MIB and SNMP definitions to get the mes- sage out from your own shell scripts. As an example, the command shown here utilizes a well-known monitoring tool’s SNMP and MIB data to allow a trap to be sent. /usr/local/bin/trapclient $MON_HOST $MIB_NUM $TRAP_NUM $TRAP_TEXT In the previous command the MON_HOST variable represents the enterprise man- agement workstation. The MIB_NUM variable represents the specific code for the MIB parameter. The TRAP_NUM variable represents the specific trap code to send, and the TRAP_TEXT is the text that is sent with the trap. This type of usage varies depending on the monitoring tool that you are using. At any rate, there are techniques that allow you to write shell scripts to send traps. The methods vary, but the basic syntax remains the same for SNMP. Summary This is one of those chapters where it is useless to write a bunch of shell scripts. I tried to show some of the techniques of monitoring applications and application processes, but the details are too varied to cover in a single chapter. I have laid down a specific process that you can utilize to build a very nice tool to monitor your systems and appli- cations. Always start with a ping! If the box is unpingable, then your first job is to get the machine booted or to call hardware support. In the next steps you have several options, including interacting with the applica- tion, as we did with a SQL+ query of an Oracle database. We also covered monitoring specific processes that are a little flaky and die every once in a while. I have two appli- cations that I have to monitor this way, and I have not had even one phone call since I put this tool in place. The key is to keep the business in business, and the best way to do that is to be very proactive. This is where good monitoring and control shell scripts make you look like gold. Remember, no one ever notices an application except when it is down! In the next chapter, we move on to study creating pseudo-random passwords. The scripts include the use of arrays in shell scripts and a practical use for computer- generated pseudo-random numbers in a shell script. See you in the next chapter! Monitoring Processes and Applications 261 263 Got security? Most of the user community does not know how to create secure pass- words that are not easy to guess. Users tend to have several passwords that they rotate. The problem with these “rotating” passwords is that they are usually easy to guess. For example, users find that birth dates, social security numbers, addresses, department names/numbers, and so on make good passwords that are easy to remember. Some- times they even use words found in any dictionary, which is a starting point for any cracker. In this chapter we are going to create a shell script that creates pseudo-random passwords. Randomness If you look at Chapter 21, “ Pseudo-Random Number Generator,” you can see the exercise that we used to create pseudo-random numbers. These numbers are not true random numbers because of the cyclical nature of how “random numbers” are created on a computer system. For example, if you always start a random number sequence with the same seed, or first number, you will always have the same sequence of numbers. In Chapter 21 we used the process ID (PID) of the current process, which was the shell script, as the seed for creating pseudo-random numbers. This use of the PID is good because PIDs are created by the system in a somewhat random nature. Now that I have lost you in random numbers you are asking, “What does a random number have to do with a password?” As we proceed, the answer will be intuitively obvious. Creating Pseudo-Random Passwords CHAPTER 10 Creating Pseudo-Random Passwords We started this chapter with a discussion on randomness because we are going to use computer-generated pseudo-random numbers, then use these generated numbers as pointers to specific array elements of keyboard characters, which are stored in the array KEYS. In this chapter you get a practical use for generating random numbers, and you thought Chapter 21 was a waste of time! The script idea goes like this: We use an external file that contains keyboard characters, one character per line. You can put any keyboard characters in this file that you want. I just went down the rows on the keyboard from left to right, starting on the top row of keys with numbers. As I went through all of the keyboard keys I then added a second set of numbers from the number keypad, as well as all of the uppercase and lowercase characters. The nice thing about this strategy is that you have the ability to specify the exact group of characters that make a valid password in your shop. Country-specific keyboards, which use characters other than those of the U.S. keyboards, also benefit from this strategy. Once we have the keyboard file created, we load the keyboard data into an array. Don’t panic! Korn shell arrays are easy to work with, as you will see in the scripting section as well as in the array introduction section. When we have all of the array ele- ments loaded, then we know how many total elements we have to work with. Using techniques described in Chapter 21, we create pseudo-random numbers between one and the total number of array elements, n. With an array pointer, which is nothing more than a pseudo-random number, pointing to an individual character, we add the spe- cific character to build a text string. The default length of this character string, which is the password we are creating, is eight characters; however, this can be changed on the command line to make the password longer or shorter by adding an integer value specifying the new password length. The final step is to print the password to the screen. We also add two command-line switch options, -n and -m. The -n switch specifies that the user wants to create a new keyboard data file. The -m switch specifies that the user wants to print a password page. In our shop we are required to put some passwords, such as root, in multiple security envelopes to be locked in a safe, just in case. To remove the risk of typos, I print the password page, which has three copies of the password data on the same page, and cut the sheet up into three pieces. I then fold each of the three slips of paper and seal each one in a security envelope and give them to my Admin Manager. As you can see, creating passwords is not something that I take lightly! Weak pass- words make for a real security risk, and as a Systems Administrator you need to take a proactive approach to create secure passwords that are as random as you can make them. This chapter is a valuable asset to any security team as well as for the common user. Syntax As with any of our scripting sessions we first need the correct syntax for the primary commands that we are going to use in the shell script. In this case we need to introduce 264 Chapter 10 arrays and the commands that are used to work with the array and the array elements. There is a lot more than loading an array to creating this shell script. When we get to the scripting section you will see the other tasks that I have in mind, and you can pick up a pointer or two from the chapter. Arrays In a Korn shell we can create one-dimensional arrays. A one-dimensional array con- tains a sequence of array elements, which are like the boxcars connected together on a train track. An array element can be just about anything, except for another array. I know, you’re thinking that you can use an array to access an array to create two- and three-dimensional arrays. If this can be done, it is beyond the scope of this book. For our task we are going to load our array with single-character array elements that are loaded into the array from an external file. An array element can be a text string, number, line of text, print queue name, or just about anything you can list. Loading an Array An array can be loaded in two ways. You can define and load the array in one step with the set -A command, or you can load the array one element at a time. Both techniques are shown here. Defining and Loading Array “KEYS” in One Step set -A KEYS q w e r t y u i o p \[ \] a s d f g h j k l \$ Notice in this preceding list that the characters [, ], and $ have been escaped to remove their special function by adding a backslash character. If we had not escaped these characters, then errors, and strange behavior, may occur as you tried to load or display the array elements. You will see this on a larger scale in the shell script. Also remember that if you enclose a list in double quotes or single tic marks it is treated as a single array element, not as individual array elements. Loading Array “KEYS” One Array Element at a Time The second option for loading the array KEYS is to use a while read loop and use a file as input to the while loop. In this example we load the array elements one at a time using a counter to index the KEYS array. X=0 while read ARRAY_ELEMENT do ((X = X + 1)) KEYS[$X]=$ARRAY_ELEMENT done < $ARRAY_ELEMENT_FILE Creating Pseudo-Random Passwords 265 The first loading option, which uses the set -A command, requires that you hard- code the keyboard layout into the shell script, which removes much of the flexibility that you want when restricting or expanding password content. Using the while loop method we can use an external file and load this file with any characters that we want, and we can have as many or as few characters defined for passwords as we like. We can also duplicate characters and change the order of the characters any way we wish. As the counter is incremented on each while loop iteration, we load the array ele- ments in sequential order, starting with array elements 1, KEYS[1]. When we get to the end of the file, we know how many elements we have loaded in the array by the value of the array counter, $X. To see the specific value of array element 22, you can use the following syntax: # echo ${KEYS[22]} ; As you can see from the response, the 22nd array element that was loaded is a semi- colon character (;). We can also display the number of array elements using either of the following two options: # echo ${#KEYS[*]) # echo ${#KEYS[@]) Notice that we started with array element 1, one. The Korn shell also supports array element 0, zero, but the pseudo-random numbers we create start with one, not zero. We will look at arrays more closely as we write our shell script. Building the Password Creation Script I want to explain this shell script one step at a time, and we have a lot to cover, so let’s get started. First, you need to understand the order of execution and each task that is involved in this script. Order of Appearance As usual, we start out by defining the variables that are required for this script. The fol- lowing section shows the variables that are defined for this shell script. Define Variables LENGTH=8 # Default password length. NOTIFICATION_LIST=<Manager notification list> # Persons to notify if the password is revealed or the “glass has been broken.” DEFAULT_PRINTER=<printer or queue name> # Default printer to print the password report. 266 Chapter 10 SCRIPT=$(basename $0) # The name of this shell script with the directory path removed. OUTFILE=/tmp/tmppwd.out # Temporary hold file for the printer report. KEYBOARD_FILE=/scripts/keyboard.keys # File containing keyboard characters. PRINT_PASSWORD_MANAGER_REPORT=<TRUE or Anything else> # Print report flag. RANDOM=$$ # Initializes the random seed to the PID of the shell script, which is pretty random. The purpose of each of these variables is shown after the pound sign (#) on each line. Define Functions We have six functions to go through in this section. The functions described here are listed in their order of appearance in the shell script, mk_passwd.ksh. In each of the function descriptions there is a function listing for you to follow through. in_range_random_number Function Description The Korn shell provides an environment variable called—you guessed it—RANDOM. This pseudo-random number generator uses a seed as a starting point to create all future numbers in the sequence. The initial seed is used to create a pseudo-random number. This resulting number is used for the next seed to create the next random number, and so on. As you would expect, if you always start generating your numbers with the same seed each time, you will get the exact same number sequence each time. To change the repeatability we need to have a mechanism to vary the initial seed each time we start generating numbers. I like to use the current process ID (PID) of the shell script because this number will vary widely and is an easy way to change the seed value each time we start generating numbers. We often want to limit the range of numbers not to exceed a user-defined maximum. An example is creating lottery numbers between 1 and the maximum number, which might be 36. We are going to use the modulo arithmetic operator to reduce all numbers to a fixed set of numbers between [0 N-1], which is called modulo N arithmetic. We are going to use this pseudo-random number to index array elements in the KEYS array. For our number range we need a script-defined maximum value, which we will assign to a variable called UPPER_LIMIT. This UPPER_LIMIT variable is defined when the KEYS array has been loaded because it represents the total number of ele- ments that are contained in the KEYS array. The modulo operator is the percent sign (%), and we use this operator the same way that you use the forward slash (/) in divi- sion. We still use the RANDOM Korn shell variable to get a new pseudo-random number. This time, though, we are going to use the following equation to limit the number to not exceed the script-defined maximum. RANDOM_NUMBER=$(($RANDOM % $UPPER_LIMIT + 1)) Creating Pseudo-Random Passwords 267 Notice that we added one to the result. Using the preceding equation will produce a pseudo-random number between 1 and the script-defined $UPPER_LIMIT, which is the total number of elements in the KEYS array. The function using this equation is in_range_random_number and is shown in Listing 10.1. function in_range_random_number { # Create a pseudo-random number less than or equal # to the $UPPER_LIMIT value, which is defined in the # main body of the shell script. RANDOM_NUMBER=$(($RANDOM % $UPPER_LIMIT + 1)) echo “$RANDOM_NUMBER” } Listing 10.1 in_range_random_number function listing. The function in Listing 10.1 assumes that the RANDOM variable seed has been initial- ized in the main body of the shell script and that a script-defined UPPER_LIMIT variable has been set. This function will produce numbers between 1 and the script-defined maximum value. load_default_keyboard Function Description As it turns out, you can add as many, or as few, characters to the $KEYBOARD_FILE file. What if the user wants a quick startup and an easy way to create this required file? This is the reason why I added this function to the mk_passwd.ksh shell script. There are two mechanisms for loading a default keyboard layout. The first way is when the shell script is unable to locate the $KEYBOARD_FILE on the system. In this case the user is prompted to load the default keyboard layout. The second option is to add -n as a command-line switch. We will get to parsing command-line switches later in this chapter. In either of the two situations the user is still prompted before the $KEYBOARD_FILE is loaded with default keyboard layout. Other than prompting the user to load the default keyboard layout, we need to sup- ply a list of keyboard characters to load into the file. At this point let’s look at the func- tion code in Listing 10.2 and cover the details at the end. function load_default_keyboard { # If a keyboard data file does not exist then the user # is prompted to load the standard keyboard data into the # $KEYBOARD_FILE, which is defined in the main body of Listing 10.2 load_default_keyboard function listing. 268 Chapter 10 # the shell script. clear # Clear the screen echo “\nLoad the default keyboard data file? (Y/N): \c” read REPLY case $REPLY in y|Y) : ;; *) echo “\nSkipping the load of the default keyboard file \n” return ;; esac cat /dev/null > $KEYBOARD_FILE echo “\nLoading the Standard Keyboard File \c” # Loop through each character in the following list and # append each character to the $KEYBOARD_FILE file. This # produces a file with one character on each line. for CHAR in \` 1 2 3 4 5 6 7 8 9 0 \- \= \\ q w e r t y u i o \ p \[ \] a s d f g h j k l \; \’ z x c v b n m \, \ \. \/ \\ \~ \! \@ \# \$ \% \^ \& \* \( \) _ \+ \| \ Q W E R T Y U I O P \{ \} A S D F G H J K L \: \” \ Z X C V B N M \< \> \? \| \. 0 1 2 3 4 5 6 7 8 9 \/ \ \* \- \+ do echo “$CHAR” >> $KEYBOARD_FILE done echo “\n\n\t Done \n” sleep 1 Listing 10.2 load_default_keyboard function listing. (continued) Now I want to direct your attention to the for loop in Listing 10.2, which is in bold- face text. The idea is to loop through each character one at a time and append the char- acter to the $KEYBOARD_FILE. The result is a file that contains the keyboard layout, listed one character per line. The file shows one character per line to make it easier to load the file and the KEYS array. In the list of characters please notice that most of the nonalphanumeric characters are preceded by a backslash (\), not just the Korn shell special characters. As we discussed previously, this backslash is used to escape the special meaning of these characters. Creating Pseudo-Random Passwords 269 When you precede a special character with the backslash, you are able to use the char- acter as a literal character, just like the alphanumeric characters, and if a backslash pre- cedes the other non-alphanumeric characters, it is ignored. The list of characters that are escaped is shown here: ` ! @ # $ % ^ & * ( ) _ - = + [ ] { } On each loop iteration one character is appended to the $KEYBOARD_FILE using the following command: echo “$CHAR” >> $KEYBOARD_FILE When the file is loaded, which happens extremely fast, we notify the user that the load is complete and then sleep for one second. I added this sleep 1 at the end of this function because the load happened so fast that the user needed a second to see the message. check_for_and_create_keyboard_file Function Description Is this function name descriptive enough? I like to know exactly what a function is used for by reading the name of the function. The purpose of this function is to check for the existence of the $KEYBOARD_FILE and to prompt the user to load the default keyboard layout into the $KEYBOARD_FILE. The user has the option to load the default data or not to load it. If the user declines to load the keyboard data file, then this script will not work. To get around this little problem, we just notify the user of this ERROR and exit the shell script. When the user gets the error message, he or she is also informed of the name of the missing file and a description of what the script expects in the file—specifically, one keyboard character per line. The full function is shown in Listing 10.3. function check_for_and_create_keyboard_file { # If the $KEYBOARD_FILE does not exist then # ask the user to load the “standard” keyboard # layout, which is done with the load_default_keyboard # function. if [ ! -s $KEYBOARD_FILE ] then echo “\n\nERROR: Missing Keyboard File” echo “\n\nWould You Like to Load the” echo “Default Keyboard Layout?” echo “\n\t(Y/N): \c” typeset -u REPLY=FALSE read REPLY if [[ $REPLY != Y ]] then Listing 10.3 check_for_and_create_keyboard_file function listing. 270 Chapter 10 [...]... this shell script are to remove the $OUTFILE, if it exists, and then prompt the user to press ENTER to clear the screen and exit We do not want to leave a password on the screen for anyone to read That is it for the steps involved to create the mk_passwd.ksh shell script The entire shell script is shown in Listing 10. 15 Pay particular attention to the boldface text throughout the mk_passwd.ksh shell. .. a chance to change this Listing 10. 15 mk_passwd.ksh shell script listing (continues) 2 85 286 Chapter 10 # printer at execution time DEFAULT_PRINTER=”hp4@yogi” SCRIPT=$(basename $0) OUTFILE=”/tmp/tmppdw.file” KEYBOARD_FILE=/scripts/keyboard.keys PRINT_PASSWORD_MANAGER_REPORT=”TO_BE_SET” RANDOM=$$ # Initialize the random number seed to the # process ID (PID) of this shell script ####################################################... #################################################### # # Clear the screen and exit echo “\n\nPress ENTER to Clear the Screen and EXIT: \c” read X clear # End of mk_passwd.ksh shell script Listing 10. 15 mk_passwd.ksh shell script listing (continued) This was an interesting shell script to create I hope you picked up some pointers in this chapter I tried to add as many script options to this script as desirable but not make... process table, and it no longer exists The more common exit signals are 1, 2, 3, and 15 For a complete list of exit signals see Chapter 1, or enter kill -l (that’s ell) on the command line Our trap is shown here: trap ‘trap_exit; exit 2’ 1 2 3 15 When a trapped exit signal is detected, in this case signals 1, 2, 3, or 15, the trap executes the two commands enclosed within the single tic marks, (‘ commands... file \n” Listing 10. 15 mk_passwd.ksh shell script listing (continued) Creating Pseudo-Random Passwords return ;; esac cat /dev/null > $KEYBOARD_FILE echo “\nLoading the Standard Keyboard File \c” # Loop through each character in the following list and # append each character to the $KEYBOARD_FILE file This # produces a file with one character on each line for CHAR in \` 1 2 3 4 5 6 7 8 9 0 - = \\ q... echo “Default Keyboard Layout?” echo “\n\t(Y/N): \c” typeset -u REPLY=FALSE read REPLY if [ $REPLY != Y ] then echo “\n\nERROR: This shell script cannot operate” echo “without a keyboard data file located in” echo “\n==> $KEYBOARD_FILE\n” Listing 10. 15 mk_passwd.ksh shell script listing (continues) 287 288 Chapter 10 echo “\nThis file expects one character per line.” echo “\n\t EXITING \n” exit 3 else... #################################################### # Set a trap trap ‘trap_exit;exit 2’ 1 2 3 15 #################################################### # # Check for a keyboard data file check_for_and_create_keyboard_file #################################################### ############### LOAD THE ARRAY ##################### Listing 10. 15 mk_passwd.ksh shell script listing (continues) 291 292 Chapter 10 ####################################################... 2 3 4 5 6 7 8’ is # the default “for” loop list FOR_COUNT=$( X=0 while ((X < LENGTH)) do # Build the list here ((X = X + 1)) echo “$X “ done ) #################################################### # # Create the pseudo-random password in this section clear # Clear the screen PW= # Initialize the password to NULL # Build the password using random numbers to grab array Listing 10. 15 mk_passwd.ksh shell. .. zero This test code is shown here 2 75 276 Chapter 10 # Check command line arguments - $# < 3 if (($# > 3)) then usage exit 1 fi Notice that we used the mathematical test here One thing to note about the syntax of this test is that for user-, or script-defined variables we do not use the dollar sign ($) in front of the variable For shell variables you must use the shell notation here, too If the number... is produced by this script It usually takes me 5 to 10 tries to get a password that I may be able to remember Don’t stop at the first one—keep going until you get a password that you like but is not guessable Other Uses? Sure, there are other uses for this shell script Any time that you need a pseudo-random list of keyboard characters, you can use this shell script to create the list License key is . creating this shell script. When we get to the scripting section you will see the other tasks that I have in mind, and you can pick up a pointer or two from the chapter. Arrays In a Korn shell we. variable. For shell variables you must use the shell notation here, too. If the number of arguments on the command line exceeds three, then we display the usage function and exit the shell script. pseudo-random passwords. The scripts include the use of arrays in shell scripts and a practical use for computer- generated pseudo-random numbers in a shell script. See you in the next chapter! Monitoring

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