Mastering unix shell scripting phần 5 doc

70 575 0
Mastering unix shell scripting phần 5 doc

Đ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

As you can see in Listing 9.6, this is not much of a query, but it is all that we need. This SQL script, my_sql_query.sql, is used in the sqlplus function in Listing 9.7. Notice in this function, simple_SQL_query, that the sqlplus command statement requires a username, password, and an Oracle SID name to work. See the function code in Listing 9.7. function simple_SQL_query { USER=oracle PASSWD=oracle SID=yogidb sqlplus ${USER}/${PASSWD}@$SID @my_sql_query.sql } Listing 9.7 simple_SQL_query function listing. The function shown in Listing 9.7 can be shortened further, if you are logged in to the system as the oracle user or executing a script as the oracle user. If these conditions are met then you can run a simpler version of the previous sqlplus, as shown in List- ing 9.8, with the output of the query; however, the Oracle Listener is not tested as in the previous sqlplus statement in Listing 9.7. The sqlplus command in Listing 9.8 should be run on the local machine. [oracle@yogi] sqlplus / @/usr/local/bin/mysql_query.sql SQL*Plus: Release 8.1.7.0.0 - Production on Wed Aug 7 16:07:30 2002 (c) Copyright 2000 Oracle Corporation. All rights reserved. Connected to: Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production With the Partitioning option JServer Release 8.1.7.4.0 - Production USERNAME USER_ID ACCOUNT_STATUS LOCK_DATE EXPIRY_DATE DEFAULT_TABLESPACE TEMPORARY_TABLESPACE CREATED INITIAL_RSRC_CONSUMER_GROUP Listing 9.8 Example of an SQL+ Oracle query. 258 Chapter 9 EXTERNAL_NAME OPS$ORACLE 940 OPEN USERS TEMP 18-APR-2002 Disconnected from Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production With the Partitioning option JServer Release 8.1.7.4.0 - Production Listing 9.8 Example of an SQL+ Oracle query. (continued) This is about as simple as it gets! You can check the return code from the sqlplus command shown in Listing 9.8. If it is zero, then the query worked. If the return code is nonzero, then the query failed and the database should be considered down. In any case, the Database Administrator needs to be notified of this condition. Checking If the HTTP Server/Application Is Working Some applications use a Web browser interface. For this type of application we can use a command-line browser, such as linx, to attempt to reach a specific URL, which in turn should bring up the specified application Web page. The function shown in List- ing 9.9 utilizes the linx command-line browser to check both the HTTP server and the Web page presented by the specified URL, which is passed to the function in the $1 argument. check_HTTP_server () { LINX=”/usr/local/bin/lynx” # Define the location of the linx program URL=$1 # Capture the target URL in the $1 position URLFILE=/tmp/HTTP.$$ # Define a file to hold the URL output ########################################### $LINX “$URL” > $URLFILE # Attempt to reach the target URL if (($? != 0)) # If the URL is unreachable - No Connection Listing 9.9 check_HTTP_server function listing. (continues) Monitoring Processes and Applications 259 then echo “\n$URL - Unable to connect\n” cat $URLFILE else # Else the URL was found while read VER RC STATUS # This while loop is fed from the bottom # after the “done” using input redirection do case $RC in # Check the return code in the $URLFILE 200|401|301|302) # These are valid return codes! echo “\nHTTP Server is OK\n” ;; *) # Anything else is not a valid return code echo “\nERROR: HTTP Server Error\n” ;; esac done < $URLFILE fi rm -f $URLFILE } Listing 9.9 check_HTTP_server function listing. (continued) This is a nice function in Listing 9.9 for checking the status of a Web server and also to see if an application URL is accessible. You should test this function against doing the same task manually using a graphical browser. This has been tested on an applica- tion front-end, and it works as expected; however, a good test is recommended before implementing this, or any other code, in this book. You know all about the disclaimer stuff. (I am really not even here writing this book, or so the disclaimer says.) Other Things to Consider As with any code that is written, it can always be improved. Each of the functions and code segments presented in this chapter are just that, code segments. When you are monitoring applications, code like this is only one part of a much bigger shell script, at least it should be. The monitoring should start at the lowest level, which is sending a ping to the application host to ensure that the machine is powered on and booted. Then we apply more layers as we try to build a script that will allow us to debug the problem. I have presented only a few ideas; it is your job to work out the details for your environment. 260 Chapter 9 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 [...]... 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 ####################################################... 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... 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. .. The commands include running the trap_exit function that removes the $OUTFILE file; then the script exits with a return code of 2, which has been defined as a trap exit for this shell script Checking for the Keyboard File This shell script is useless without a keyboard data file and cannot execute anything To check for the existence of the $KEYBOARD_FILE, we execute the check_for_ and_create_keyboard_file... a list of numbers to loop through This list of numbers represents the length of the password The default list is 1 2 3 4 5 6 7 8 The code to build this list is shown in Listing 10.12 # Produce the “for” loop list of elements that represent # the length of the password: ‘1 2 3 4 5 6 7 8’ is # the default “for” loop list FOR_COUNT=$( Listing 10.12 Code to build a for loop list of numbers (continues) . 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: 09/08/2014, 16:20

Từ khóa liên quan

Mục lục

  • Chapter 9 Monitoring Processes and Applications

    • Remote Monitoring with Secure Shell

      • Checking If the HTTP Server/Application Is Working

      • Other Things to Consider

        • Application APIs and SNMP Traps

        • Summary

        • Chapter 10 Creating Pseudo-Random Passwords

          • Randomness

          • Creating Pseudo-Random Passwords

          • Syntax

            • Arrays

              • Loading an Array

              • Building the Password Creation Script

                • Order of Appearance

                  • Define Variables

                  • Define Functions

                  • Testing and Parsing Command-Line Arguments

                  • Beginning of Main

                    • Setting a Trap

                    • Checking for the Keyboard File

                    • Loading the "KEYS" Array

                    • Using the LENGTH Variable to Build a Loop List

                    • Building a New Pseudo-Random Password

                    • Printing the Manager's Password Report for Safe Keeping

                    • Other Options to Consider

                      • Password Reports?

                      • Which Password?

                      • Other Uses?

                      • Summary

                      • Chapter 11 Monitor for Stale Disk Partitions

                        • AIX Logical Volume Manager (LVM)

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

Tài liệu liên quan