系统负载监控

  1. #!/bin/ksh  
  2.  
  3.  
  4. SECS=300   # Defines the number of seconds for each sample  
  5. INTERVAL=2    # Defines the total number of sampling intervals  
  6. STATCOUNT=0   # Initialize a loop counter to 0, zero  
  7. OS=$(uname)   # Defines the UNIX flavor  
  8.  
  9. ###################################################  
  10. ##### SETUP THE ENVIRONMENT FOR EACH OS HERE ######  
  11. ###################################################  
  12.  
  13. # These "F-numbers" point to the correct field in the  
  14. # command output for each UNIX flavor.  
  15.  
  16. case $OS in  
  17. AIX|HP-UX)   SWITCH='-t'  
  18.              F1=3  
  19.              F2=4  
  20.              F3=5  
  21.              F4=6  
  22.              echo "\nThe Operating System is $OS\n"  
  23.              ;;  
  24. Linux|SunOS) SWITCH='-c'  
  25.              F1=1  
  26.              F2=2  
  27.              F3=3  
  28.              F4=4  
  29.              echo "\nThe Operating System is $OS\n"  
  30.              ;;  
  31.  
  32. *) echo "\nERROR: $OS is not a supported operating system\n"  
  33.    echo "\n\t...EXITING...\n"  
  34.    exit 1  
  35.    ;;  
  36. esac  
  37.  
  38. ###################################################  
  39. ######## BEGIN GATHERING STATISTICS HERE ##########  
  40. ###################################################  
  41.  
  42. echo "Gathering CPU Statistics using vmstat...\n"  
  43. echo "There are $INTERVAL sampling periods with"  
  44. echo "each interval lasting $SECS seconds"  
  45. echo "\n...Please wait while gathering statistics...\n"  
  46.  
  47. # Use "iostat" to monitor the CPU utilization and  
  48. # remove all lines that contain alphabetic characters  
  49. # and blank spaces. Then use the previously defined  
  50. # field numbers, for example F1=4,to point directly  
  51. # to the 4th position, for this example. The syntax  
  52. # for this techniques is ==>  $'$F1'.  
  53.  
  54. iostat $SWITCH $SECS $INTERVAL | egrep -v '[a-zA-Z]|^$' \  
  55.           | awk '{print $'$F1', $'$F2', $'$F3', $'$F4'}' \  
  56.           | while read FIRST SECOND THIRD FOURTH  
  57. do  
  58.   if ((STATCOUNT == 1)) # Loop counter to get the second set  
  59.   then                  # of data produces by "iostat"  
  60.  
  61.       case $OS in # Show the results based on the UNIX flavor  
  62.       AIX)  
  63.             echo "\nUser part is ${FIRST}%"  
  64.             echo "System part is ${SECOND}%"  
  65.             echo "Idle part is ${THIRD}%"  
  66.             echo "I/O wait state is ${FOURTH}%\n"  
  67.             ;;  
  68.       HP-UX|Linux)  
  69.             echo "\nUser part is ${FIRST}%"  
  70.             echo "Nice part is ${SECOND}%"  
  71.             echo "System part is ${THIRD}%"  
  72.             echo "Idle time is ${FOURTH}%\n"  
  73.             ;;  
  74.       SunOS)  
  75.             echo "\nUser part is ${FIRST}%"  
  76.             echo "System part is ${SECOND}%"  
  77.             echo "I/O Wait is ${THIRD}%"  
  78.             echo "Idle time is ${FOURTH}%\n"  
  79.             ;;  
  80.       esac  
  81.  
  82.   fi  
  83.   ((STATCOUNT = STATCOUNT + 1)) # Increment the loop counter  
  84. done 
  1. #!/bin/ksh  
  2.  
  3.  
  4. SECS=30  # Defines the number of seconds for each sample  
  5. INTERVAL=10 # Defines the total number of sampling intervals  
  6. OS=$(uname) # Defines the UNIX flavor  
  7.  
  8. ###################################################  
  9. ##### SETUP THE ENVIRONMENT FOR EACH OS HERE ######  
  10. ###################################################  
  11.  
  12. # These "F-numbers" point to the correct field in the  
  13. # command output for each UNIX flavor.  
  14.  
  15. case $OS in  
  16. AIX|HP-UX|SunOS)     
  17.        F1=2  
  18.        F2=3  
  19.        F3=4  
  20.        F4=5  
  21.        echo "\nThe Operating System is $OS\n"  
  22.        ;;  
  23. Linux)  
  24.        F1=3  
  25.        F2=4  
  26.        F3=5  
  27.        F4=6  
  28.        echo "\nThe Operating System is $OS\n"  
  29.        ;;  
  30. *) echo "\nERROR: $OS is not a supported operating system\n"  
  31.    echo "\n\t...EXITING...\n"  
  32.    exit 1  
  33.    ;;  
  34. esac  
  35.  
  36. ###################################################  
  37. ######## BEGIN GATHERING STATISTICS HERE ##########  
  38. ###################################################  
  39.  
  40. echo "Gathering CPU Statistics using sar...\n"  
  41. echo "There are $INTERVAL sampling periods with"  
  42. echo "each interval lasting $SECS seconds"  
  43. echo "\n...Please wait while gathering statistics...\n"  
  44.  
  45. # This "sar" command take $INTERVAL samples, each lasting  
  46. # $SECS seconds. The average of this output is captured.  
  47.  
  48. sar $SECS $INTERVAL | grep Average \  
  49.           | awk '{print $'$F1', $'$F2', $'$F3', $'$F4'}' \  
  50.           | while read FIRST SECOND THIRD FOURTH  
  51. do  
  52.       # Based on the UNIX Flavor, tell the user the   
  53.       # result of the statistics gathered.  
  54.  
  55.       case $OS in  
  56.       AIX|HP-UX|SunOS)  
  57.             echo "\nUser part is ${FIRST}%"  
  58.             echo "System part is ${SECOND}%"  
  59.             echo "I/O wait state is ${THIRD}%"  
  60.             echo "Idle time is ${FOURTH}%\n"  
  61.             ;;  
  62.       Linux)  
  63.             echo "\nUser part is ${FIRST}%"  
  64.             echo "Nice part is ${SECOND}%"  
  65.             echo "System part is ${THIRD}%"  
  66.             echo "Idle time is ${FOURTH}%\n"  
  67.             ;;  
  68.       esac  
  69. done 
  1. #!/bin/ksh  
  2.  
  3.  
  4. MAXLOAD=2.00  
  5. typeset -i INT_MAXLOAD=$MAXLOAD  
  6.  
  7. # Find the correct field to extract based on how long  
  8. # the system has been up, or since the last reboot.  
  9.  
  10. if $(uptime | grep day | grep min >/dev/null)  
  11. then  
  12.      FIELD=11  
  13. elif $(uptime | grep day | grep hrs >/dev/null)  
  14. then  
  15.      FIELD=11  
  16. elif $(uptime | grep day >/dev/null)  
  17. then  
  18.      FIELD=10  
  19. elif $(uptime | grep min >/dev/null)  
  20. then  
  21.      FIELD=9  
  22. else  
  23.      FIELD=8  
  24. fi  
  25.  
  26. ###################################################  
  27. ######## BEGIN GATHERING STATISTICS HERE ##########  
  28. ###################################################  
  29.  
  30. echo "\nGathering System Load Average using the \"uptime\" command\n"  
  31.  
  32. # This next command statement extracts the latest   
  33. # load statistics no matter what the UNIX flavor is.  
  34.  
  35. LOAD=$(uptime | sed s/,//g | awk '{print $'$FIELD'}')  
  36.  
  37. # We need an integer representation of the $LOAD  
  38. # variable to do the test for the load going over   
  39. # the set threshold defince by the $INT_MAXLOAD  
  40. # variable  
  41.  
  42. typeset -i INT_LOAD=$LOAD  
  43.  
  44. # If the current load has exceeded the threshold then   
  45. # issue a warning message. The next step always shows  
  46. # the user what the current load and threshold values  
  47. # are set to.  
  48.  
  49. ((INT_LOAD >= INT_MAXLOAD)) && echo "\nWARNING: System load has \  
  50. reached ${LOAD}\n"   
  51.  
  52. echo "\nSystem load value is currently at ${LOAD}"  
  53. echo "The load threshold is set to ${MAXLOAD}\n" 
  1. #!/bin/ksh  
  2.  
  3.  
  4. SECONDS=300  # Defines the number of seconds for each sample  
  5. INTERVAL=2   # Defines the total number of sampling intervals  
  6. STATCOUNT=0  # Initialize a loop counter to 0, zero  
  7. OS=$(uname)  # Defines the UNIX flavor  
  8.  
  9. ###################################################  
  10. ##### SETUP THE ENVIRONMENT FOR EACH OS HERE ######  
  11. ###################################################  
  12.  
  13. # These "F-numbers" point to the correct field in the  
  14. # command output for each UNIX flavor.  
  15.  
  16. case $OS in  
  17. AIX)   # AIX has four relative columns in the output   
  18.        F1=14  
  19.        F2=15  
  20.        F3=16  
  21.        F4=17  
  22.  
  23.        echo "\nThe Operating System is $OS\n"  
  24.        ;;  
  25. HP-UX) # HP-UX only has three relative columns in the output  
  26.        F1=16  
  27.        F2=17  
  28.        F3=18  
  29.        F4=1   # This "F4=1" is bogus and not used for HP-UX  
  30.  
  31.        echo "\nThe Operating System is $OS\n"  
  32.        ;;  
  33. Linux) # Linux only has three relative columns in the output  
  34.        F1=14  
  35.        F2=15  
  36.        F3=16  
  37.        F4=1   # This "F4=1" is bogus and not used for Linux  
  38.  
  39.        echo "\nThe Operating System is $OS\n"  
  40.        ;;  
  41. SunOS) # SunOS only has three relative columns in the output  
  42.        F1=20  
  43.        F2=21  
  44.        F3=22  
  45.        F4=1   # This "F4=1" is bogus and not used for SunOS  
  46.  
  47.        echo "\nThe Operating System is $OS\n"  
  48.        ;;  
  49. *) echo "\nERROR: $OS is not a supported operating system\n"  
  50.    echo "\n\t...EXITING...\n"  
  51.    exit 1  
  52.    ;;  
  53. esac  
  54.  
  55. ###################################################  
  56. ######## BEGIN GATHERING STATISTICS HERE ##########  
  57. ###################################################  
  58.  
  59. echo "Gathering CPU Statistics using vmstat...\n"  
  60. echo "There are $INTERVAL sampling periods with"  
  61. echo "each interval lasting $SECONDS seconds"  
  62. echo "\n...Please wait while gathering statistics...\n"  
  63.  
  64. # Use "vmstat" to monitor the CPU utilization and   
  65. # remove all lines that contain alphabetic characters  
  66. # and blank spaces. Then use the previously defined   
  67. # field numbers, for example F1=20,to point directly  
  68. # to the 20th position, for this example. The syntax  
  69. # for this techniques is ==>  $'$F1', and points directly  
  70. # to the $20 positional parameter.  
  71.  
  72. vmstat $SECONDS $INTERVAL | egrep -v '[a-zA-Z]|^$' \  
  73.           | awk '{print $'$F1', $'$F2', $'$F3', $'$F4'}' \  
  74.           | while read FIRST SECOND THIRD FORTH  
  75. do  
  76.   if ((STATCOUNT == 1)) # Loop counter to get the second set  
  77.   then                  # of data produces by "vmstat"  
  78.  
  79.       case $OS in  # Show the results based on the UNIX flavor  
  80.       AIX)  
  81.             echo "\nUser part is ${FIRST}%"  
  82.             echo "System part is ${SECOND}%"  
  83.             echo "Idle part is ${THIRD}%"  
  84.             echo "I/O wait state is ${FORTH}%\n"  
  85.             ;;  
  86.       HP-UX|Linux|SunOS)  
  87.             echo "\nUser part is ${FIRST}%"  
  88.             echo "System part is ${SECOND}%"  
  89.             echo "Idle time is ${THIRD}%\n"  
  90.             ;;  
  91.       esac  
  92.  
  93.   fi  
  94.   ((STATCOUNT = STATCOUNT + 1)) # Increment the loop counter  
  95. done 

页面调度与交换空间监控

  1. #!/usr/bin/ksh  
  2.  
  3.  
  4. PC_LIMIT=65            # Upper limit of Swap space percentage  
  5.                        # before notification  
  6.  
  7. THISHOST=$(hostname)   # Host name of this machine  
  8.  
  9. echo "\nSwap Space Report for $THISHOST\n"  
  10. date  
  11.  
  12. function SUN_swap_mon  
  13. {  
  14. SW_USED=$(swap -s | awk '{print $9}' | cut -dk -f1)  
  15. SW_FREE=$(swap -s | awk '{print $11}' | cut -dk -f1)  
  16. ((SW_TOTAL = SW_USED + SW_FREE))  
  17. PERCENT_USED=$(bc <<EOF  
  18. scale=4  
  19. ($SW_USED / $SW_TOTAL) * 100  
  20. EOF  
  21. )  
  22.  
  23. PERCENT_FREE=$(bc <<EOF  
  24. scale=4  
  25. ($SW_FREE / $SW_TOTAL) * 100  
  26. EOF  
  27. )  
  28.  
  29. # Convert the KB measurements to MB measurements  
  30.  
  31. ((SW_TOTAL_MB = SW_TOTAL / 1000))  
  32. ((SW_USED_MB  = SW_USED / 1000))  
  33. ((SW_FREE_MB  = SW_FREE / 1000))  
  34.  
  35. # Produce the remaining part of the report  
  36.  
  37. echo "\nTotal Amount of Swap Space:\t${SW_TOTAL_MB}MB"  
  38. echo "Total KB of Swap Space Used:\t${SW_USED_MB}MB"  
  39. echo "Total KB of Swap Space Free:\t${SW_FREE_MB}MB"  
  40. echo "\nPercent of Swap Space Used:\t${PERCENT_USED}%"  
  41. echo "\nPercent of Swap Space Free:\t${PERCENT_FREE}%"  
  42.  
  43. # Grab the integer portion of the percent used  
  44.  
  45. INT_PERCENT_USED=$(echo $PERCENT_USED | cut -d. -f1)  
  46.  
  47. # Check to see if the percentage used maxmum threshold  
  48. # has beed exceeded  
  49.  
  50. if (( PC_LIMIT <= INT_PERCENT_USED ))  
  51. then  
  52.     # Percent used has exceeded the threshold, send notification  
  53.  
  54.     tput smso # Turn on reverse video!  
  55.     echo "\n\nWARNING: Swap Space has Exceeded the ${PC_LIMIT}% Upper Limit!\n"  
  56.     tput rmso # Turn off reverse video!  
  57. fi  
  58.  
  59. echo "\n"  
  60. }  
  61.  
  62.  
  63. function Linux_swap_mon  
  64. {  
  65.  
  66. free -m | grep -i swap | while read junk SW_TOTAL SW_USED SW_FREE  
  67. do  
  68. PERCENT_USED=$(bc <<EOF  
  69. scale=4  
  70. ($SW_USED / $SW_TOTAL) * 100  
  71. EOF  
  72. )  
  73.  
  74. PERCENT_FREE=$(bc <<EOF  
  75. scale=4  
  76. ($SW_FREE / $SW_TOTAL) * 100  
  77. EOF  
  78. )  
  79.  
  80.      # Produce the rest of the paging space report:  
  81.      echo "\nTotal Amount of Swap Space:\t${SW_TOTAL}MB"  
  82.      echo "Total KB of Swap Space Used:\t${SW_USED}MB"  
  83.      echo "Total KB of Swap Space Free:\t${SW_FREE}MB"  
  84.      echo "\nPercent of Swap Space Used:\t${PERCENT_USED}%"  
  85.      echo "\nPercent of Swap Space Free:\t${PERCENT_FREE}%"  
  86.  
  87.      # Grap the integer portion of the percent used to  
  88.      # test for the over limit threshold  
  89.  
  90.      INT_PERCENT_USED=$(echo $PERCENT_USED | cut -d. -f1)  
  91.  
  92.      if (( PC_LIMIT <= INT_PERCENT_USED ))  
  93.      then  
  94.           tput smso  
  95.           echo "\n\nWARNING: Paging Space has Exceeded the \  
  96. ${PC_LIMIT}% Upper Limit!\n"  
  97.           tput rmso  
  98.      fi  
  99.  
  100. done  
  101.  
  102. echo "\n"  
  103. }  
  104.  
  105. ###########################################################  
  106.  
  107. function HP_UX_swap_mon  
  108. {  
  109. ############# CAPTURE AND PROCESS THE DATA ################  
  110.  
  111. # Start a while read loop by using the piped in input from  
  112. # the swapinfo -tm command output.  
  113.  
  114.  
  115. swapinfo -tm | grep dev | while read junk SW_TOTAL SW_USED \  
  116.                                SW_FREE PERCENT_USED junk2  
  117. do  
  118.     # Calculate the percentage of free swap space  
  119.  
  120.     ((PERCENT_FREE = 100 - $(echo $PERCENT_USED | cut -d% -f1) ))  
  121.  
  122.     echo "\nTotal Amount of Swap Space:\t${SW_TOTAL}MB"  
  123.     echo "Total MB of Swap Space Used:\t${SW_USED}MB"  
  124.     echo "Total MB of Swap Space Free:\t${SW_FREE}MB"  
  125.     echo "\nPercent of Swap Space Used:\t${PERCENT_USED}"  
  126.     echo "\nPercent of Swap Space Free:\t${PERCENT_FREE}%"  
  127.  
  128.     # Check for paging space exceeded the predefined limit  
  129.  
  130.     if (( PC_LIMIT <= $(echo $PERCENT_USED | cut -d% -f1) ))  
  131.     then  
  132.         # Swap space is over the predefined limit, send notification  
  133.  
  134.        tput smso # Turn on reverse video!  
  135.          echo "\n\nWARNING: Swap Space has Exceeded the\  
  136.  ${PC_LIMIT}% Upper Limit!\n"  
  137.          tput rmso # Turn reverse video off!  
  138.     fi  
  139.  
  140. done  
  141.  
  142. echo "\n"  
  143. }  
  144.  
  145. ###########################################################  
  146.  
  147. function AIX_paging_mon  
  148. {  
  149. ################ DEFINE VARIABLES HERE ####################  
  150.  
  151. PAGING_STAT=/tmp/paging_stat.out # Paging Stat hold file  
  152.  
  153. ###########################################################  
  154. ############# CAPTURE AND PROCESS THE DATA ################  
  155.  
  156. # Load the data in a file without the column headings  
  157.  
  158. lsps -s | tail +2 > $PAGING_STAT  
  159.  
  160. # Start a while loop and feed the loop from the bottom using  
  161. # the $PAGING_STAT file as redirected input  
  162.  
  163. while read TOTAL PERCENT  
  164. do  
  165.      # Clean up the data by removing the suffixes  
  166.      PAGING_MB=$(echo $TOTAL | cut -d 'MB' -f1)  
  167.      PAGING_PC=$(echo $PERCENT | cut -d% -f1)  
  168.  
  169.      # Calculate the missing data: %Free, MB used and MB free  
  170.      (( PAGING_PC_FREE = 100 - PAGING_PC ))  
  171.      (( MB_USED = PAGING_MB * PAGING_PC / 100 ))  
  172.      (( MB_FREE = PAGING_MB - MB_USED ))  
  173.  
  174.      # Produce the rest of the paging space report:  
  175.      echo "\nTotal MB of Paging Space:\t$TOTAL"  
  176.      echo "Total MB of Paging Space Used:\t${MB_USED}MB"  
  177.      echo "Total MB of Paging Space Free:\t${MB_FREE}MB"  
  178.      echo "\nPercent of Paging Space Used:\t${PERCENT}"  
  179.      echo "\nPercent of Paging Space Free:\t${PAGING_PC_FREE}%"  
  180.  
  181.      # Check for paging space exceeded the predefined limit  
  182.      if ((PC_LIMIT <= PAGING_PC))  
  183.      then  
  184.           # Paging space is over the limit, send notification  
  185.  
  186.           tput smso  # Turn on reverse video!  
  187.  
  188.           echo "\n\nWARNING: Paging Space has Exceeded the ${PC_LIMIT}% \  
  189. Upper Limit!\n"  
  190.  
  191.           tput rmso  # Turn off reverse video  
  192.      fi  
  193.  
  194. done < $PAGING_STAT  
  195.  
  196. rm -f $PAGING_STAT  
  197.  
  198. # Add an extra new line to the output  
  199.  
  200. echo "\n"  
  201. }  
  202.  
  203. ###########################################################  
  204. ################## BEGINNING OF MAIN ######################  
  205. ###########################################################  
  206.  
  207. ###########################################################  
  208. ################ DEFINE VARIABLES HERE ####################  
  209.  
  210. PC_LIMIT=65            # Upper limit of Swap space percentage  
  211.                        # before notification  
  212.  
  213. THISHOST=$(hostname)   # Host name of this machine  
  214.  
  215. ###########################################################  
  216.  
  217. # Find the Operating System and execute the correct function  
  218.  
  219. case $(uname) in  
  220.  
  221.      AIX) AIX_paging_mon  
  222.      ;;  
  223.      HP-UX) HP_UX_swap_mon  
  224.      ;;  
  225.      Linux) Linux_swap_mon  
  226.      ;;  
  227.      SunOS) SUN_swap_mon  
  228.      ;;  
  229. esac  
  230.  
  231. # End of all-in-one_swapmon.ksh 

进程监控

  1. #!/bin/ksh  
  2.  
  3. typeset -u RUN_PRE_EVENT  # Force to UPPERCASE  
  4. typeset -u RUN_STARTUP_EVENT  # Force to UPPERCASE  
  5. typeset -u RUN_POST_EVENT # force to UPPERCASE  
  6.  
  7. RUN_PRE_EVENT='N'  # A 'Y' will execute, anything else will not  
  8. RUN_STARTUP_EVENT='Y' # A 'Y' will execute, anything else will not  
  9. RUN_POST_EVENT='Y' # A 'Y' will execute, anything else will not  
  10.  
  11. LOGFILE="/tmp/proc_status.log"  
  12. [[ ! -s $LOGFILE ]] && touch $LOGFILE  
  13.  
  14. SCRIPT_NAME=$(basename $0)  
  15. TTY=$(tty)  
  16. INTERVAL="1" # Seconds between sampling  
  17. JOBS=  
  18.  
  19. ####################################################  
  20. ############# DEFINE FUNCTIONS HERE ################  
  21. ####################################################  
  22.  
  23. usage ()  
  24. {  
  25. echo "\n\n\t*****USAGE ERROR*****"  
  26. echo "\n\nUSAGE:  $SCRIPT_NAME  seconds  process"  
  27. echo "\nWill monitor the specified process for the"  
  28. echo "specified number of seconds."  
  29. echo "\nUSAGE:  $SCRIPT_NAME  [-s|-S seconds] [-m|-M minutes]"  
  30. echo "        [-h|-H hours] [-d|-D days] [-p|-P process]\n"  
  31. echo "\nWill monitor the specified process for number of"  
  32. echo "seconds specified within -s seconds, -m minutes,"  
  33. echo "-h hours and -d days.  Any combination of command"  
  34. echo "switches can be used.\n"  
  35. echo "\nEXAMPLE: $SCRIPT_NAME  300  dtcalc"  
  36. echo "\n\nEXAMPLE: $SCRIPT_NAME  -m 5 -p dtcalc"  
  37. echo "\nBoth examples will monitor the dtcalc process"  
  38. echo "for 5 minutes.  Can specify days, hours, minutes"  
  39. echo "and seconds, using -d, -h, -m and -s\n\n"  
  40. }  
  41.  
  42. ####################################################  
  43.  
  44. trap_exit ()  
  45. {  
  46. # set -x # Uncommant to debug this function  
  47. # Log an ending time for process monitoring  
  48. echo "INTERRUPT: Program Received an Interrupt...EXITING..." > $TTY  
  49. echo "INTERRUPT: Program Received an Interrupt...EXITING..." >> $LOGFILE  
  50. TIMESTAMP=$(date +%D@%T) # Get a new time stamp...  
  51. echo "MON_STOPPED: Monitoring for $PROCESS ended ==> $TIMESTAMP\n" \  
  52.       >> $TTY  
  53. echo "MON_STOPPED: Monitoring for $PROCESS ended ==> $TIMESTAMP\n" \  
  54.       >> $LOGFILE  
  55. echo "LOGFILE: All Events are Logged ==> $LOGFILE \n" > $TTY  
  56.  
  57. # Kill all functions  
  58. JOBS=$(jobs -p)  
  59. if [[ ! -z $JOBS && $JOBS != '' && $JOBS != '0' ]]  
  60. then  
  61.       kill $(jobs -p) 2>/dev/null 1>&2  
  62. fi  
  63. return 2  
  64. }  
  65.  
  66. ####################################################  
  67.  
  68. pre_event_script ()  
  69. {  
  70. # Put anything that you want to execute BEFORE the   
  71. # monitored process STARTS in this function  
  72.  
  73. : # No-OP - Needed as a place holder for an empty function  
  74. # Comment Out the Above colon, ':'  
  75.  
  76. PRE_RC=$?  
  77. return $PRE_RC  
  78. }  
  79.  
  80. ####################################################  
  81. startup_event_script ()  
  82. {  
  83. # Put anything that you want to execute WHEN, or AS, the  
  84. # monitored process STARTS in this function  
  85.  
  86. : # No-OP - Needed as a place holder for an empty function  
  87. # Comment Out the Above colon, ':'  
  88.  
  89. STARTUP_RC=$?  
  90. return $STARTUP_RC  
  91. }  
  92.  
  93. ####################################################  
  94.  
  95.  
  96. post_event_script ()  
  97. {  
  98. # Put anything that you want to execute AFTER the   
  99. # monitored process ENDS in this function  
  100.  
  101. : # No-OP - Need as a place holder for an empty function  
  102. # Comment Out the Above colon, ':'  
  103.  
  104. POST_RC=$?  
  105. return $POST_RC  
  106. }  
  107.  
  108. ####################################################  
  109.  
  110. test_string ()  
  111. {  
  112. if (( $# != 1 ))  
  113. then  
  114.     echo 'ERROR'  
  115.     return  
  116. fi  
  117.  
  118. C_STRING=$1  
  119.  
  120. case $C_STRING in  
  121.  
  122.      +([0-9])) echo  'POS_INT' # Integer >= 0  
  123.                ;;  
  124.      +([-0-9])) echo 'NEG_INT' # Integer < 0  
  125.                ;;  
  126.      +([a-z])) echo  'LOW_CASE'   # lower case text  
  127.                ;;  
  128.      +([A-Z])) echo  'UP_CASE'    # UPPER case text   
  129.                ;;  
  130.      +([a-z]|[A-Z])) echo 'MIX_CASE' # MIxed CAse text  
  131.                ;;  
  132.                *) echo 'UNKNOWN'  # Anything else   
  133. esac  
  134. }  
  135.  
  136. ####################################################  
  137.  
  138. proc_watch ()  
  139. {  
  140. # set -x # Uncomment to debug this function  
  141.  
  142. while :     # Loop Forever!!  
  143. do  
  144.     case $RUN in  
  145.     'Y')  
  146.           # This will run the startup_event_script, which is a function  
  147.  
  148.           if [[ $RUN_STARTUP_EVENT = 'Y' ]]  
  149.           then  
  150.              echo "STARTUP EVENT: Executing Startup Event Script..." > $TTY  
  151.              echo "STARTUP EVENT: Executing Startup Event Script..." >> $LOGFILE  
  152.  
  153.              startup_event_script # USER DEFINED FUNCTION!!!  
  154.              RC=$?  
  155.              if (( "RC" == 0 ))  
  156.              then  
  157.                   echo "SUCCESS: Startup Event Script Completed RC - ${RC}"\  
  158.                         > $TTY  
  159.                   echo "SUCCESS: Startup Event Script Completed RC - ${RC}"\  
  160.                         >> $LOGFILE  
  161.  
  162.              else  
  163.                   echo "FAILURE: Startup Event Script FAILED RC - ${RC}"\  
  164.                         > $TTY  
  165.                   echo "FAILURE: Startup Event Script FAILED RC - ${RC}"\  
  166.                         >> $LOGFILE  
  167.  
  168.              fi  
  169.           fi  
  170.  
  171.           integer PROC_COUNT='-1' # Reset the Counters  
  172.           integer LAST_COUNT='-1'  
  173.  
  174.           # Loop until the process(es) end(s)  
  175.  
  176.           until (( "PROC_COUNT" == 0 ))  
  177.           do  
  178.                # This function is a Co-Process. $BREAK checks to see if  
  179.                # "Program Interrupt" has taken place. If so BREAK will  
  180.                # be 'Y' and we exit both the loop and function.  
  181.  
  182.                read BREAK  
  183.                if [[ $BREAK = 'Y' ]]  
  184.                then  
  185.                      return 3  
  186.                fi  
  187.                PROC_COUNT=$(ps -ef | grep -v "grep $PROCESS" \  
  188.                            | grep -v $SCRIPT_NAME \  
  189.                            | grep $PROCESS| wc -l) >/dev/null 2>&1  
  190.  
  191.                if (( "LAST_COUNT" > 0 && "LAST_COUNT" != "PROC_COUNT" ))  
  192.                then  
  193.                     # The Process Count has Changed...  
  194.                     TIMESTAMP=$(date +%D@%T)  
  195.                     # Get a list of the PID of all of the processes  
  196.                     PID_LIST=$(ps -ef | grep -v "grep $PROCESS" \  
  197.                            | grep -v $SCRIPT_NAME \  
  198.                            | grep $PROCESS | awk '{print $2}')  
  199.  
  200.                     echo "PROCESS COUNT: $PROC_COUNT $PROCESS\  
  201.  Processes Running ==> $TIMESTAMP" >> $LOGFILE &  
  202.                     echo "PROCESS COUNT: $PROC_COUNT $PROCESS\  
  203.  Processes Running ==> $TIMESTAMP" > $TTY  
  204.               
  205.                     echo ACTIVE PIDS: $PID_LIST >> $LOGFILE &  
  206.                     echo ACTIVE PIDS: $PID_LIST > $TTY  
  207.                fi  
  208.                LAST_COUNT=$PROC_COUNT  
  209.                sleep $INTERVAL # Needed to reduce CPU load!  
  210.           done  
  211.  
  212.           RUN='N' # Turn the RUN Flag Off  
  213.  
  214.           TIMESTAMP=$(date +%D@%T)  
  215.           echo "ENDING PROCESS: $PROCESS END time  ==>\  
  216.  $TIMESTAMP" >> $LOGFILE &  
  217.           echo "ENDING PROCESS: $PROCESS END time  ==>\  
  218.  $TIMESTAMP" > $TTY  
  219.  
  220.           # This will run the post_event_script, which is a function  
  221.  
  222.           if [[ $RUN_POST_EVENT = 'Y' ]]  
  223.           then  
  224.               echo "POST EVENT: Executing Post Event Script..."\  
  225.                     > $TTY  
  226.               echo "POST EVENT: Executing Post Event Script..."\  
  227.                     >> $LOGFILE  
  228.  
  229.               post_event_script # USER DEFINED FUNCTION!!!  
  230.               RC=$?  
  231.               if (( "RC" == 0 ))  
  232.               then  
  233.                   echo "SUCCESS: Post Event Script Completed RC -\  
  234.                         ${RC}" > $TTY  
  235.                   echo "SUCCESS: Post Event Script Completed RC - ${RC}"\  
  236.                         >> $LOGFILE  
  237.               else  
  238.                   echo "FAILURE: Post Event Script FAILED RC - ${RC}"\  
  239.                         > $TTY  
  240.                   echo "FAILURE: Post Event Script FAILED RC - ${RC}"\  
  241.                         >> $LOGFILE  
  242.               fi  
  243.           fi    
  244.      ;;  
  245.  
  246.      'N')  
  247.           # This will run the pre_event_script, which is a function  
  248.  
  249.           if [[ $RUN_PRE_EVENT = 'Y' ]]  
  250.           then  
  251.              echo "PRE EVENT: Executing Pre Event Script..." > $TTY  
  252.              echo "PRE EVENT: Executing Pre Event Script..." >> $LOGFILE  
  253.  
  254.              pre_event_script # USER DEFINED FUNCTION!!!  
  255.              RC=$?  
  256.              if (( "RC" == 0 ))  
  257.              then  
  258.                   echo "SUCCESS: Pre Event Script Completed RC - ${RC}"\  
  259.                         > $TTY  
  260.                   echo "SUCCESS: Pre Event Script Completed RC - ${RC}"\  
  261.                         >> $LOGFILE  
  262.              else  
  263.                   echo "FAILURE: Pre Event Script FAILED RC - ${RC}"\  
  264.                         > $TTY  
  265.                   echo "FAILURE: Pre Event Script FAILED RC - ${RC}"\  
  266.                         >> $LOGFILE  
  267.              fi  
  268.           fi  
  269.  
  270.           echo "WAITING: Waiting for $PROCESS to startup...Monitoring..."  
  271.  
  272.           integer PROC_COUNT='-1' # Initialize to a fake value  
  273.  
  274.           # Loop until at least one process starts  
  275.  
  276.           until (( "PROC_COUNT" > 0 ))  
  277.           do  
  278.                # This is a Co-Process. This checks to see if a "Program  
  279.                # Interrupt" has taken place. If so BREAK will be 'Y' and  
  280.                # we exit both the loop and function  
  281.  
  282.                read BREAK  
  283.                if [[ $BREAK = 'Y' ]]  
  284.                then  
  285.                      return 3  
  286.                fi  
  287.                PROC_COUNT=$(ps -ef | grep -v "grep $PROCESS" \  
  288.                      | grep -v $SCRIPT_NAME | grep $PROCESS | wc -l) \  
  289.                        >/dev/null 2>&1  
  290.  
  291.                sleep $INTERVAL # Needed to reduce CPU load!  
  292.           done  
  293.  
  294.           RUN='Y' # Turn the RUN Flag On  
  295.  
  296.           TIMESTAMP=$(date +%D@%T)  
  297.  
  298.           PID_LIST=$(ps -ef | grep -v "grep $PROCESS" \  
  299.                      | grep -v $SCRIPT_NAME \  
  300.                      | grep $PROCESS | awk '{print $2}')  
  301.  
  302.           if (( "PROC_COUNT" == 1 ))  
  303.           then  
  304.                echo "START PROCESS: $PROCESS START time ==>\  
  305.  $TIMESTAMP" >> $LOGFILE &  
  306.                echo ACTIVE PIDS: $PID_LIST >> $LOGFILE &  
  307.                echo "START PROCESS: $PROCESS START time ==>\  
  308.  $TIMESTAMP" > $TTY  
  309.                echo ACTIVE PIDS: $PID_LIST > $TTY  
  310.           elif (( "PROC_COUNT" > 1 ))  
  311.           then  
  312.                echo "START PROCESS: $PROC_COUNT $PROCESS \  
  313. Processes Started: START time ==> $TIMESTAMP" >> $LOGFILE &  
  314.                echo ACTIVE PIDS: $PID_LIST >> $LOGFILE &  
  315.                echo "START PROCESS: $PROC_COUNT $PROCESS \  
  316. Processes Started: START time ==> $TIMESTAMP" > $TTY  
  317.                echo ACTIVE PIDS: $PID_LIST > $TTY  
  318.           fi  
  319.      ;;  
  320.    esac  
  321. done  
  322. }  
  323.  
  324. ####################################################  
  325. ############## START OF MAIN #######################  
  326. ####################################################  
  327.  
  328. ### SET A TRAP ####  
  329.  
  330. trap 'BREAK='Y';print -p $BREAK 2>/dev/null;trap_exit\  
  331.  2>/dev/null;exit 0' 1 2 3 15  
  332.  
  333. BREAK='N' # The BREAK variable is used in the co-process proc_watch  
  334. PROCESS=  
  335. PROCESS_ID=$$  
  336. integer TOTAL_SECONDS=0  
  337.  
  338. # Check commnand line arguments  
  339.  
  340. if (( $# > 10 || $# < 2 ))  
  341. then  
  342.      usage  
  343.      exit 1  
  344. fi  
  345.  
  346. # Check to see if only the seconds and a process are  
  347. # the only arguments  
  348.  
  349. if [[ ($# -eq 2) && ($1 != -*) && ($2 != -*) ]]  
  350. then  
  351.      NUM_TEST=$(test_string $1)  
  352.      if [[ "$NUM_TEST" = 'POS_INT' ]]  
  353.      then  
  354.           TOTAL_SECONDS=$1  
  355.           PROCESS=$2  
  356.      else  
  357.           usage  
  358.           exit 1  
  359.      fi  
  360. else  
  361.      # Since getopts does not care what arguments it gets lets   
  362.      # do a quick sanity check to make sure that we only have  
  363.      # between 2 and 10 arguments and the first one must start  
  364.      # with a -* (hyphen and anything), else usage error  
  365.  
  366.      case "$#" in  
  367.      [2-10]) if [[ $1 != -* ]]; then  
  368.                  usage; exit 1  
  369.              fi  
  370.           ;;  
  371.      esac  
  372.  
  373.      HOURS=0   # Initialize all to zero  
  374.      MINUTES=0  
  375.      SECS=0  
  376.      DAYS=0  
  377.  
  378.      # Use getopts to parse the command line arguments  
  379.  
  380.      # For each $OPTARG for DAYS, HOURS, MINUTES and DAYS check to see  
  381.      # that each one is an integer by using the check_string function  
  382.  
  383.      while getopts ":h:H:m:M:s:S:d:D:P:p:" TIMED 2>/dev/null  
  384.      do  
  385.        case $TIMED in  
  386.        h|H) [[ $(test_string $OPTARG) != 'POS_INT' ]] && usage && exit 1  
  387.             (( HOURS = $OPTARG * 3600 )) # 3600 seconds per hour  
  388.             ;;  
  389.        m|H) [[ $(test_string $OPTARG) != 'POS_INT' ]] && usage && exit 1  
  390.             (( MINUTES = $OPTARG * 60 )) # 60 seconds per minute  
  391.             ;;  
  392.        s|S) [[ $(test_string $OPTARG) != 'POS_INT' ]] && usage && exit 1  
  393.             SECS="$OPTARG"            # seconds are seconds  
  394.             ;;  
  395.        d|D) [[ $(test_string $OPTARG) != 'POS_INT' ]] && usage && exit 1  
  396.             (( DAYS = $OPTARG * 86400 )) # 86400 seconds per day  
  397.             ;;  
  398.        p|P) PROCESS=$OPTARG              # process can be anything  
  399.             ;;  
  400.         \?) usage                        # USAGE ERROR  
  401.             exit 1  
  402.             ;;  
  403.          :) usage  
  404.             exit 1  
  405.             ;;  
  406.          *) usage  
  407.             exit 1  
  408.             ;;  
  409.        esac  
  410.      done  
  411. fi  
  412.  
  413. # We need to make sure that we have a process - sanity check  
  414.  
  415. if [[ -z "$PROCESS" || "$PROCESS" = '' ]]  
  416. then  
  417.      usage  
  418.      exit 1  
  419. fi  
  420.  
  421. # Check to see that TOTAL_SECONDS was not previously set  
  422.  
  423. if (( TOTAL_SECONDS == 0 ))  
  424. then  
  425.      # Add everything together if anything is > 0  
  426.  
  427.      if [[ $SECS -gt 0 || $MINUTES -gt 0 || $HOURS -gt 0 \  
  428.                           || $DAYS -gt 0 ]]  
  429.      then  
  430.           (( TOTAL_SECONDS = SECS + MINUTES + HOURS + DAYS ))  
  431.      fi  
  432.           SECONDS_LEFT=$TOTAL_SECONDS # Set the countdown varaible...  
  433.  
  434. fi  
  435.  
  436. # Last Sanity Check!  
  437.  
  438. if (( TOTAL_SECONDS <= 0 )) || [ -z $PROCESS ]  
  439. then  
  440.      # Either There are No Seconds to Count or the  
  441.      # $PROCESS Variable is Null...USAGE ERROR...  
  442.  
  443.      usage  
  444.      exit 1  
  445. fi  
  446.  
  447. echo "\nCurrently running $PROCESS processes:\n" > $TTY  
  448. ps -ef | grep -v "grep $PROCESS" | grep -v $SCRIPT_NAME \  
  449.        | grep $PROCESS > $TTY  
  450.  
  451. PROC_RC=$? # Get the initial state of the monitored function  
  452.  
  453. echo >$TTY # Send a blank line to the screen  
  454.  
  455. (( PROC_RC != 0 )) && echo "\nThere are no $PROCESS processes running\n"  
  456.  
  457. if (( PROC_RC == 0 )) # The Target Process(es) is/are running...  
  458. then  
  459.      RUN='Y' # Set the RUN flag to true, or yes.  
  460.  
  461.      integer PROC_COUNT # Strips out the "padding" for display  
  462.  
  463.      PROC_COUNT=$(ps -ef | grep -v "grep $PROCESS" | grep -v \  
  464.                   $SCRIPT_NAME | grep $PROCESS | wc -l) >/dev/null 2>&1  
  465.      if (( PROC_COUNT == 1 ))  
  466.      then  
  467.           echo "The $PROCESS process is currently running...Monitoring...\n"  
  468.      elif (( PROC_COUNT > 1 ))  
  469.      then  
  470.           print "There are $PROC_COUNT $PROCESS processes currently running\  
  471. ...Monitoring...\n"  
  472.      fi  
  473. else  
  474.      echo "The $PROCESS process is not currently\  running...monitoring..."  
  475.      RUN='N' # Set the RUN flag to false, or no.  
  476. fi  
  477.  
  478. TIMESTAMP=$(date +%D@%T) # Time that this script started monitoring  
  479.  
  480. # Get a list of the currently active process IDs  
  481.  
  482. PID_LIST=$(ps -ef | grep -v "grep $PROCESS" \  
  483.                   | grep -v $SCRIPT_NAME  \  
  484.                   | grep $PROCESS | awk '{print $2}')  
  485.  
  486. echo "MON_STARTED: Monitoring for $PROCESS began ==> $TIMESTAMP" \  
  487.       | tee -a $LOGFILE  
  488. echo ACTIVE PIDS: $PID_LIST | tee -a $LOGFILE  
  489.  
  490.  
  491. proc_watch |&  # Create a Background Co-Process!!  
  492. WATCH_PID=$!   # Get the process of the last background job!  
  493.  
  494. # Start the Count Down!  
  495.  
  496. integer SECONDS_LEFT=$TOTAL_SECONDS  
  497.  
  498. while (( SECONDS_LEFT > 0 ))  
  499. do  
  500.      print -p $BREAK 2>/dev/null  
  501.  
  502.      (( SECONDS_LEFT = SECONDS_LEFT - 1 ))  
  503.      sleep 1 # Seconds Countdown  
  504. done  
  505.  
  506. # Finished - Normal Timeout Exit...  
  507.  
  508. TIMESTAMP=$(date +%D@%T) # Get a new time stamp...  
  509. echo "MON_STOPPED: Monitoring for $PROCESS ended ==> $TIMESTAMP\n" \  
  510.       | tee -a $LOGFILE  
  511.  
  512. echo "LOGFILE: All Events are Logged ==> $LOGFILE \n"  
  513.  
  514. # Tell the proc_watch function to break out of the loop and die  
  515.  
  516. BREAK='Y'  
  517. print -p $BREAK 2>/dev/null  
  518.  
  519. kill $WATCH_PID 2>/dev/null  
  520.  
  521. exit 0  
  522.  
  523. # End of Script 
此文章由 flyinweb 于 2009-07-05 17:11:41 编辑

本日志由 flyinweb 于 2009-07-05 17:04:09 发表,目前已经被浏览 3917 次,评论 0 次;

作者添加了以下标签: shell系统负载监控

引用通告:http://www.517sou.net/Article/128/Trackback.ashx

评论订阅:http://www.517sou.net/Article/128/Feeds.ashx

评论列表

    暂时没有评论
(必填)
(必填,不会被公开)