SlideShare ist ein Scribd-Unternehmen logo
1 von 20
CIS 216
Dan Morrill
 Top
    Gets you a list of processes that are consuming the CPU
 htop
    Near real time list of running processes by CPU, includes
     scrolling, and mouse support
 vmstat
    Provides information about processes, memory, paging, I/O,
     traps and CPU
 w/who/finger
    Provides information about users that are consuming
     resources on the computer
 ps (ps –ef )
    Lists all the currently running processes on a Linux computer
 pgrep/pkill
   pgrep <process name> lists the PID of the process based on
    name
   pkill <process name> sends a specific kill signal (default
    sigterm or shutdown) to a matching process
 free
   Shows the current memory usage of the system. Shows
    physical and swap memory
 mpstat
   mpstat 2 5 - shows five set of data of global statistics among
    all processors at two second intervals.
   mpstat –P ALL 2 5 - shows 5 sets of statistics for all processors
    at two second intervals.
 iostat
   reports CPU statists for devices and partitions
    (including NFS Samba partitions)
 pmap
   This command reports memory map of a process. This
    can be used to find memory usage of the process.
 Set the debug mode for this, you will want it,
 remember what each debug mode switch does
  1. # set -n : Uncomment to check script syntax, without
     execution.
  2. #     Note: Do not forget to put the comment back in
     or
  3. #      the shell script will not execute!
  4. # set -x : Uncomment to debug this shell script
 PROC_MON=`basename $0`                  # Defines the script_name variable as the
  file name of this script
  LOGFILE="/home/ganesh/procmon.log"         # Shows log file and where
  located
  [[ ! -s $LOGFILE ]] && touch $LOGFILE   # This checks to see if the file exists
                 # if not it creates one.
  TTY=$(tty)                 # Current tty or pty
  PROCESS="ssh"                # This will define which process to monitor
  SLEEP_TIME="1"                # This is the sleep time in second between
  monitoring

  txtred=$(tput setaf 1) # Red: will indicate a failed process and the information
  txtgrn=$(tput setaf 2) # Green: this is successful process information
  txtylw=$(tput setaf 3) # Yellow: this is used to show cautionary information
  txtrst=$(tput sgr0) # resets text
 function exit_trap     # this is the behavior of the trap
  signal
  {
  # Log an ending time for process monitoring
    DATE=$(date +%D)
    TIME=$(date +%T) # Get a new timestamp...
    echo "$DATE @ $TIME: Monitoring for $PROCESS
  terminated" >> $LOGFILE & # this will create an entry in
  the logfile
    echo "$DATE @ $TIME: ${txtred}Monitoring for
  $PROCESS terminated${txtrst}"
  #kill all functions
  kill -9 $(jobs -p) 2>/dev/null
 Set the trap to see if the process exits
 trap 'exit_trap; exit 0' 1 2 3 15

  # this will see if process is running if not will start it

  ps aux | grep "$PROCESS" | grep -v "grep $PROCESS" 
  | grep -v $PROC_MON >/dev/null
   if (( $? != 0 ))
    then
       DATE=$(date +%D)
       TIME=$(date +%T)
       echo
       echo "$DATE @ $TIME: $PROCESS is NOT active...starting $PROCESS.." >> $LOGFILE & #
    creates
                                # an entry in the logfile
       echo "$DATE @ $TIME: ${txtylw}$PROCESS is NOT active...starting $PROCESS..${txtrst}"
       echo
    sleep 1
       service $PROCESS start &
       echo "$DATE @ $TIME: $PROCESS has been started..." >> $LOGFILE & #puts an enrty in logfile
         else # this will say what to do if process is already running
       echo -e "n" # a blank line
       DATE=$(date +%D)
       TIME=$(date +%T)
       echo "$DATE @ $TIME: $PROCESS is currnetly RUNNING..." >> $LOGFILE & # puts entry in logfile
       echo "$DATE @ $TIME: ${txtgrn}$PROCESS is currently RUNNING...${txtrst}"
    fi
 while (( RC == 0 )) # this will loop until the return code is not zero
  do
     ps aux | grep $PROCESS | grep -v "grep $PROCESS" 
     | grep -v $PROC_MON >/dev/null 2>&1
     if (( $? != 0 )) # check the return code
     then
    echo
     DATE=$(date +%D)
    TIME=$(date +%T)
    echo "$DATE @ $TIME: $PROCESS has STOPPED..." >> $LOGFILE & # entry
  in logfile
       echo "$DATE @ $TIME: ${txtred}$PROCESS has STOPPED...${txtrst}"
    echo
    service $PROCESS start &
    echo "$DATE @ $TIME: $PROCESS has RESTARTED..." >> $LOGFILE & #
  ENTRY IN LOGFILE
    echo "$DATE @ $TIME: ${txtgrn}$PROCESS has RESTARTED...${txtrst}"
       sleep 1
      ps aux | grep $PROCESS | grep -v "grep $PROCESS" 
       | grep -v $PROC_MON >/dev/null 2>&1
       if (( $? != 0 ))  # This will check the return code
       then
       echo
       DATE=$(date +%D)         # New time stamp
       TIME=$(date +%T)
       echo "$DATE @ $TIME: $PROCESS failed to restart..." >> $LOGFILE
    & #entry in logfile
       echo "$DATE @ $TIME: ${txtred}$PROCESS failed to
    restart...${txtrst}"
       exit 0
    fi
    fi
      sleep $SLEEP_TIME          # This is needed to reduce CPU Load!!!
    done
 Process is hard coded in the script
   # Process to be monitored
    target="ssh"
 wait_time="10“
 This is in seconds
 log_file="procmon.log"
 script_failure="0"
   # Monitor process and restart if necessary
    for attempt in 1 2 3
    do
       ps aux | grep "$target" | grep -v "grep $target" 
       | grep -v $script_name >/dev/null
       if [ $? != 0 ]
       then
          log_time=$(date)
          echo
          echo "$(tput setaf 3)$target is not running. Attempt will be made to restart. This is attempt
    $attempt of 3.$(tput sgr0)"
          echo >>$log_file
          echo "$log_time: $target is not running. Restarting. Attempt $attempt of 3.">>$log_file
          echo
          service $target start &
          sleep 2 # Pause to prevent false positives from restart attempt.
       else
          attempt="3"
       fi
    done
    sleep 2 # Pause to prevent false positives from restart attempt.
    }
   detect_failure()
    {
    ps aux | grep "$target" | grep -v "grep $target" 
    | grep -v $script_name >/dev/null
    if [ $? != 0 ]
    then
       log_time=$(date)
       echo
       echo "$(tput setaf 1)$target is not running after 3 attempts. Process has failed and
    cannot be restarted. $(tput sgr0)" # Report failure to user
       echo "This script will now close."
       echo "">>$log_file
       echo "$log_time: $target cannot be restarted.">>$log_file # Log failure
       script_failure="1" # Set failure flag
    else
       log_time=$(date)
       echo
       echo "$log_time : $target is running."
       echo "$log_time : $target is running." >> $log_file
    fi
    }
 program_closing()
  {
  # Report and log script shutdown
  log_time=$(date)
  echo
  echo "Closing ProcMon script. No further monitoring of $target will be
  performed." #Reports closing of ProcMon to user
  echo
  echo "$(tput setaf 1)$log_time: Monitoring for $target terminated. $(tput sgr0)"
  echo
  echo "$log_time: Monitoring for $target terminated.">>$log_file # Logs closing
  of ProcMon to log_file
  echo >> $log_file
  echo "***************" >> $log_file
  echo >> $log_file
  # Ensure this script is properly killed
  kill -9 > /dev/null
  }
   # Trap shutdown attempts to enable logging of shutdown
    trap 'program_closing; exit 0' 1 2 3 15
    # Inform user of purpose of script
    clear
    echo
    echo "This script will monitor $target to ensure that it is running,"
    echo "and attempt to restart it if it is not. If it is unable to"
    echo "restart after 3 attempts, it will report failure and close."
    sleep 2
    #Perform monitoring
    while [ $script_failure != "1" ]
    do
      process_monitoring # Monitors process and attempts 3 restarts if it fails.
      detect_failure # Reports failure in the event that the process does not restart.
      if [ $script_failure != "1" ]
      then
         sleep $wait_time
      fi
    done
    sleep 2
    program_closing # Logs script closure
    exit 0
Process monitoring in UNIX shell scripting

Weitere ähnliche Inhalte

Was ist angesagt?

Gitosis on Mac OS X Server
Gitosis on Mac OS X ServerGitosis on Mac OS X Server
Gitosis on Mac OS X Server
Yasuhiro Asaka
 

Was ist angesagt? (20)

How to send files to remote server via ssh in php
How to send files to remote server via ssh in phpHow to send files to remote server via ssh in php
How to send files to remote server via ssh in php
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbСтажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of PythonAnsible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Python
 
Shell Script
Shell ScriptShell Script
Shell Script
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
Unix Programming with Perl 2
Unix Programming with Perl 2Unix Programming with Perl 2
Unix Programming with Perl 2
 
Raspberry pi Part 4
Raspberry pi Part 4Raspberry pi Part 4
Raspberry pi Part 4
 
Puppet Camp 2012
Puppet Camp 2012Puppet Camp 2012
Puppet Camp 2012
 
Any event intro
Any event introAny event intro
Any event intro
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
 
Unix 5 en
Unix 5 enUnix 5 en
Unix 5 en
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regex
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
 
Shell实现的windows回收站功能的脚本
Shell实现的windows回收站功能的脚本Shell实现的windows回收站功能的脚本
Shell实现的windows回收站功能的脚本
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address InformationShell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
Gitosis on Mac OS X Server
Gitosis on Mac OS X ServerGitosis on Mac OS X Server
Gitosis on Mac OS X Server
 

Andere mochten auch

We Know Your Type
We Know Your TypeWe Know Your Type
We Know Your Type
CTIN
 
Trouble shoot with linux syslog
Trouble shoot with linux syslogTrouble shoot with linux syslog
Trouble shoot with linux syslog
ashok191
 
Module 13 - Troubleshooting
Module 13 - TroubleshootingModule 13 - Troubleshooting
Module 13 - Troubleshooting
T. J. Saotome
 
unix training | unix training videos | unix course unix online training
unix training |  unix training videos |  unix course  unix online training unix training |  unix training videos |  unix course  unix online training
unix training | unix training videos | unix course unix online training
Nancy Thomas
 

Andere mochten auch (20)

KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
 
Linux MMAP & Ioremap introduction
Linux MMAP & Ioremap introductionLinux MMAP & Ioremap introduction
Linux MMAP & Ioremap introduction
 
Chapters 3 4
Chapters 3 4Chapters 3 4
Chapters 3 4
 
We Know Your Type
We Know Your TypeWe Know Your Type
We Know Your Type
 
Keystroke dynamics
Keystroke dynamicsKeystroke dynamics
Keystroke dynamics
 
Trouble shoot with linux syslog
Trouble shoot with linux syslogTrouble shoot with linux syslog
Trouble shoot with linux syslog
 
Unixshellscript 100406085942-phpapp02
Unixshellscript 100406085942-phpapp02Unixshellscript 100406085942-phpapp02
Unixshellscript 100406085942-phpapp02
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
 
UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1
 
UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
 
UNIX - Class1 - Basic Shell
UNIX - Class1 - Basic ShellUNIX - Class1 - Basic Shell
UNIX - Class1 - Basic Shell
 
Karkha unix shell scritping
Karkha unix shell scritpingKarkha unix shell scritping
Karkha unix shell scritping
 
Module 13 - Troubleshooting
Module 13 - TroubleshootingModule 13 - Troubleshooting
Module 13 - Troubleshooting
 
APACHE
APACHEAPACHE
APACHE
 
Advanced Oracle Troubleshooting
Advanced Oracle TroubleshootingAdvanced Oracle Troubleshooting
Advanced Oracle Troubleshooting
 
Linux troubleshooting tips
Linux troubleshooting tipsLinux troubleshooting tips
Linux troubleshooting tips
 
unix training | unix training videos | unix course unix online training
unix training |  unix training videos |  unix course  unix online training unix training |  unix training videos |  unix course  unix online training
unix training | unix training videos | unix course unix online training
 
Fusion Middleware 11g How To Part 2
Fusion Middleware 11g How To Part 2Fusion Middleware 11g How To Part 2
Fusion Middleware 11g How To Part 2
 
25 Apache Performance Tips
25 Apache Performance Tips25 Apache Performance Tips
25 Apache Performance Tips
 
Sql server troubleshooting
Sql server troubleshootingSql server troubleshooting
Sql server troubleshooting
 

Ähnlich wie Process monitoring in UNIX shell scripting

Tips on how to improve the performance of your custom modules for high volume...
Tips on how to improve the performance of your custom modules for high volume...Tips on how to improve the performance of your custom modules for high volume...
Tips on how to improve the performance of your custom modules for high volume...
Odoo
 

Ähnlich wie Process monitoring in UNIX shell scripting (20)

Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
 
Counting on God
Counting on GodCounting on God
Counting on God
 
Containers: What are they, Really?
Containers: What are they, Really?Containers: What are they, Really?
Containers: What are they, Really?
 
exercises-log-management-rsyslog.pdf
exercises-log-management-rsyslog.pdfexercises-log-management-rsyslog.pdf
exercises-log-management-rsyslog.pdf
 
Really useful linux commands
Really useful linux commandsReally useful linux commands
Really useful linux commands
 
Five
FiveFive
Five
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Linux cheat sheet
Linux cheat sheetLinux cheat sheet
Linux cheat sheet
 
Shell Script Disk Usage Report and E-Mail Current Threshold Status
Shell Script  Disk Usage Report and E-Mail Current Threshold StatusShell Script  Disk Usage Report and E-Mail Current Threshold Status
Shell Script Disk Usage Report and E-Mail Current Threshold Status
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
 
Create an auto-extractible shell script linux
Create an auto-extractible shell script linuxCreate an auto-extractible shell script linux
Create an auto-extractible shell script linux
 
linux_Commads
linux_Commadslinux_Commads
linux_Commads
 
03 tk2123 - pemrograman shell-2
03   tk2123 - pemrograman shell-203   tk2123 - pemrograman shell-2
03 tk2123 - pemrograman shell-2
 
Puppi. Puppet strings to the shell
Puppi. Puppet strings to the shellPuppi. Puppet strings to the shell
Puppi. Puppet strings to the shell
 
PHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnPHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vuln
 
Phishing for Root (How I Got Access to Root on Your Computer With 8 Seconds o...
Phishing for Root (How I Got Access to Root on Your Computer With 8 Seconds o...Phishing for Root (How I Got Access to Root on Your Computer With 8 Seconds o...
Phishing for Root (How I Got Access to Root on Your Computer With 8 Seconds o...
 
Tips on how to improve the performance of your custom modules for high volume...
Tips on how to improve the performance of your custom modules for high volume...Tips on how to improve the performance of your custom modules for high volume...
Tips on how to improve the performance of your custom modules for high volume...
 
lec4.docx
lec4.docxlec4.docx
lec4.docx
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 

Mehr von Dan Morrill

Mehr von Dan Morrill (16)

Windows power shell and active directory
Windows power shell and active directoryWindows power shell and active directory
Windows power shell and active directory
 
Understanding web site analytics
Understanding web site analyticsUnderstanding web site analytics
Understanding web site analytics
 
Understanding UNIX CASE and TPUT
Understanding UNIX CASE and TPUTUnderstanding UNIX CASE and TPUT
Understanding UNIX CASE and TPUT
 
Information security principles
Information security principlesInformation security principles
Information security principles
 
Using Regular Expressions in Grep
Using Regular Expressions in GrepUsing Regular Expressions in Grep
Using Regular Expressions in Grep
 
Understanding the security_organization
Understanding the security_organizationUnderstanding the security_organization
Understanding the security_organization
 
You should ask before copying that media
You should ask before copying that mediaYou should ask before copying that media
You should ask before copying that media
 
Understanding advanced persistent threats (APT)
Understanding advanced persistent threats (APT)Understanding advanced persistent threats (APT)
Understanding advanced persistent threats (APT)
 
AWS Hadoop and PIG and overview
AWS Hadoop and PIG and overviewAWS Hadoop and PIG and overview
AWS Hadoop and PIG and overview
 
What is cloud computing
What is cloud computingWhat is cloud computing
What is cloud computing
 
Social Media Plan for CityU of Seattle
Social Media Plan for CityU of SeattleSocial Media Plan for CityU of Seattle
Social Media Plan for CityU of Seattle
 
BSIS Overview
BSIS OverviewBSIS Overview
BSIS Overview
 
Case Studies In Social Media Chinese
Case Studies In Social Media ChineseCase Studies In Social Media Chinese
Case Studies In Social Media Chinese
 
Case Studies In Social Media
Case Studies In Social MediaCase Studies In Social Media
Case Studies In Social Media
 
Turn On Tune In Step Out
Turn On Tune In Step OutTurn On Tune In Step Out
Turn On Tune In Step Out
 
Technology And The Future Of Management
Technology And The Future Of ManagementTechnology And The Future Of Management
Technology And The Future Of Management
 

Kürzlich hochgeladen

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Process monitoring in UNIX shell scripting

  • 2.  Top  Gets you a list of processes that are consuming the CPU  htop  Near real time list of running processes by CPU, includes scrolling, and mouse support  vmstat  Provides information about processes, memory, paging, I/O, traps and CPU  w/who/finger  Provides information about users that are consuming resources on the computer  ps (ps –ef )  Lists all the currently running processes on a Linux computer
  • 3.  pgrep/pkill  pgrep <process name> lists the PID of the process based on name  pkill <process name> sends a specific kill signal (default sigterm or shutdown) to a matching process  free  Shows the current memory usage of the system. Shows physical and swap memory  mpstat  mpstat 2 5 - shows five set of data of global statistics among all processors at two second intervals.  mpstat –P ALL 2 5 - shows 5 sets of statistics for all processors at two second intervals.
  • 4.  iostat  reports CPU statists for devices and partitions (including NFS Samba partitions)  pmap  This command reports memory map of a process. This can be used to find memory usage of the process.
  • 5.  Set the debug mode for this, you will want it, remember what each debug mode switch does 1. # set -n : Uncomment to check script syntax, without execution. 2. # Note: Do not forget to put the comment back in or 3. # the shell script will not execute! 4. # set -x : Uncomment to debug this shell script
  • 6.  PROC_MON=`basename $0` # Defines the script_name variable as the file name of this script LOGFILE="/home/ganesh/procmon.log" # Shows log file and where located [[ ! -s $LOGFILE ]] && touch $LOGFILE # This checks to see if the file exists # if not it creates one. TTY=$(tty) # Current tty or pty PROCESS="ssh" # This will define which process to monitor SLEEP_TIME="1" # This is the sleep time in second between monitoring txtred=$(tput setaf 1) # Red: will indicate a failed process and the information txtgrn=$(tput setaf 2) # Green: this is successful process information txtylw=$(tput setaf 3) # Yellow: this is used to show cautionary information txtrst=$(tput sgr0) # resets text
  • 7.  function exit_trap # this is the behavior of the trap signal { # Log an ending time for process monitoring DATE=$(date +%D) TIME=$(date +%T) # Get a new timestamp... echo "$DATE @ $TIME: Monitoring for $PROCESS terminated" >> $LOGFILE & # this will create an entry in the logfile echo "$DATE @ $TIME: ${txtred}Monitoring for $PROCESS terminated${txtrst}" #kill all functions kill -9 $(jobs -p) 2>/dev/null
  • 8.  Set the trap to see if the process exits  trap 'exit_trap; exit 0' 1 2 3 15 # this will see if process is running if not will start it ps aux | grep "$PROCESS" | grep -v "grep $PROCESS" | grep -v $PROC_MON >/dev/null
  • 9. if (( $? != 0 )) then DATE=$(date +%D) TIME=$(date +%T) echo echo "$DATE @ $TIME: $PROCESS is NOT active...starting $PROCESS.." >> $LOGFILE & # creates # an entry in the logfile echo "$DATE @ $TIME: ${txtylw}$PROCESS is NOT active...starting $PROCESS..${txtrst}" echo sleep 1 service $PROCESS start & echo "$DATE @ $TIME: $PROCESS has been started..." >> $LOGFILE & #puts an enrty in logfile else # this will say what to do if process is already running echo -e "n" # a blank line DATE=$(date +%D) TIME=$(date +%T) echo "$DATE @ $TIME: $PROCESS is currnetly RUNNING..." >> $LOGFILE & # puts entry in logfile echo "$DATE @ $TIME: ${txtgrn}$PROCESS is currently RUNNING...${txtrst}" fi
  • 10.  while (( RC == 0 )) # this will loop until the return code is not zero do ps aux | grep $PROCESS | grep -v "grep $PROCESS" | grep -v $PROC_MON >/dev/null 2>&1 if (( $? != 0 )) # check the return code then echo DATE=$(date +%D) TIME=$(date +%T) echo "$DATE @ $TIME: $PROCESS has STOPPED..." >> $LOGFILE & # entry in logfile echo "$DATE @ $TIME: ${txtred}$PROCESS has STOPPED...${txtrst}" echo service $PROCESS start & echo "$DATE @ $TIME: $PROCESS has RESTARTED..." >> $LOGFILE & # ENTRY IN LOGFILE echo "$DATE @ $TIME: ${txtgrn}$PROCESS has RESTARTED...${txtrst}" sleep 1
  • 11. ps aux | grep $PROCESS | grep -v "grep $PROCESS" | grep -v $PROC_MON >/dev/null 2>&1 if (( $? != 0 )) # This will check the return code then echo DATE=$(date +%D) # New time stamp TIME=$(date +%T) echo "$DATE @ $TIME: $PROCESS failed to restart..." >> $LOGFILE & #entry in logfile echo "$DATE @ $TIME: ${txtred}$PROCESS failed to restart...${txtrst}" exit 0 fi fi sleep $SLEEP_TIME # This is needed to reduce CPU Load!!! done
  • 12.  Process is hard coded in the script  # Process to be monitored target="ssh"
  • 16. # Monitor process and restart if necessary for attempt in 1 2 3 do ps aux | grep "$target" | grep -v "grep $target" | grep -v $script_name >/dev/null if [ $? != 0 ] then log_time=$(date) echo echo "$(tput setaf 3)$target is not running. Attempt will be made to restart. This is attempt $attempt of 3.$(tput sgr0)" echo >>$log_file echo "$log_time: $target is not running. Restarting. Attempt $attempt of 3.">>$log_file echo service $target start & sleep 2 # Pause to prevent false positives from restart attempt. else attempt="3" fi done sleep 2 # Pause to prevent false positives from restart attempt. }
  • 17. detect_failure() { ps aux | grep "$target" | grep -v "grep $target" | grep -v $script_name >/dev/null if [ $? != 0 ] then log_time=$(date) echo echo "$(tput setaf 1)$target is not running after 3 attempts. Process has failed and cannot be restarted. $(tput sgr0)" # Report failure to user echo "This script will now close." echo "">>$log_file echo "$log_time: $target cannot be restarted.">>$log_file # Log failure script_failure="1" # Set failure flag else log_time=$(date) echo echo "$log_time : $target is running." echo "$log_time : $target is running." >> $log_file fi }
  • 18.  program_closing() { # Report and log script shutdown log_time=$(date) echo echo "Closing ProcMon script. No further monitoring of $target will be performed." #Reports closing of ProcMon to user echo echo "$(tput setaf 1)$log_time: Monitoring for $target terminated. $(tput sgr0)" echo echo "$log_time: Monitoring for $target terminated.">>$log_file # Logs closing of ProcMon to log_file echo >> $log_file echo "***************" >> $log_file echo >> $log_file # Ensure this script is properly killed kill -9 > /dev/null }
  • 19. # Trap shutdown attempts to enable logging of shutdown trap 'program_closing; exit 0' 1 2 3 15 # Inform user of purpose of script clear echo echo "This script will monitor $target to ensure that it is running," echo "and attempt to restart it if it is not. If it is unable to" echo "restart after 3 attempts, it will report failure and close." sleep 2 #Perform monitoring while [ $script_failure != "1" ] do process_monitoring # Monitors process and attempts 3 restarts if it fails. detect_failure # Reports failure in the event that the process does not restart. if [ $script_failure != "1" ] then sleep $wait_time fi done sleep 2 program_closing # Logs script closure exit 0