SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

How to send files to remote server via ssh in php
How to send files to remote server via ssh in php
Andolasoft Inc
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
SmartTools
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Python
toddmowen
 
Shell Script
Shell Script
Adam Victor Brandizzi
 
ES6 generators
ES6 generators
Steven Foote
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
Steve Rhoades
 
Unix Programming with Perl 2
Unix Programming with Perl 2
Kazuho Oku
 
Raspberry pi Part 4
Raspberry pi Part 4
Techvilla
 
Puppet Camp 2012
Puppet Camp 2012
Server Density
 
Any event intro
Any event intro
qiang
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
rjsmelo
 
Perl: Coro asynchronous
Perl: Coro asynchronous
Shmuel Fomberg
 
Unix 5 en
Unix 5 en
Simonas Kareiva
 
Parsing JSON with a single regex
Parsing JSON with a single regex
brian d foy
 
ZeroMQ Is The Answer
ZeroMQ Is The Answer
Ian Barber
 
Shell实现的windows回收站功能的脚本
Shell实现的windows回收站功能的脚本
Lingfei Kong
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
VCP Muthukrishna
 
Bag of tricks
Bag of tricks
brian d foy
 
Javascript ES6 generators
Javascript ES6 generators
RameshNair6
 
Gitosis on Mac OS X Server
Gitosis on Mac OS X Server
Yasuhiro Asaka
 
How to send files to remote server via ssh in php
How to send files to remote server via ssh in php
Andolasoft Inc
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
SmartTools
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Python
toddmowen
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
Steve Rhoades
 
Unix Programming with Perl 2
Unix Programming with Perl 2
Kazuho Oku
 
Raspberry pi Part 4
Raspberry pi Part 4
Techvilla
 
Any event intro
Any event intro
qiang
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
rjsmelo
 
Perl: Coro asynchronous
Perl: Coro asynchronous
Shmuel Fomberg
 
Parsing JSON with a single regex
Parsing JSON with a single regex
brian d foy
 
ZeroMQ Is The Answer
ZeroMQ Is The Answer
Ian Barber
 
Shell实现的windows回收站功能的脚本
Shell实现的windows回收站功能的脚本
Lingfei Kong
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
VCP Muthukrishna
 
Javascript ES6 generators
Javascript ES6 generators
RameshNair6
 
Gitosis on Mac OS X Server
Gitosis on Mac OS X Server
Yasuhiro Asaka
 

Viewers also liked (20)

KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
Jiang Zhu
 
Linux MMAP & Ioremap introduction
Linux MMAP & Ioremap introduction
Gene Chang
 
Chapters 3 4
Chapters 3 4
sakshi_20
 
We Know Your Type
We Know Your Type
CTIN
 
Keystroke dynamics
Keystroke dynamics
Tushar Kayande
 
Trouble shoot with linux syslog
Trouble shoot with linux syslog
ashok191
 
Unixshellscript 100406085942-phpapp02
Unixshellscript 100406085942-phpapp02
Ben Mohammed Esskhayri
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
bokonen
 
UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1
Nihar Ranjan Paital
 
UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
Nihar Ranjan Paital
 
UNIX - Class1 - Basic Shell
UNIX - Class1 - Basic Shell
Nihar Ranjan Paital
 
Karkha unix shell scritping
Karkha unix shell scritping
chockit88
 
Module 13 - Troubleshooting
Module 13 - Troubleshooting
T. J. Saotome
 
APACHE
APACHE
neftaly quijano tun
 
Advanced Oracle Troubleshooting
Advanced Oracle Troubleshooting
Hector Martinez
 
Linux troubleshooting tips
Linux troubleshooting tips
Bert Van Vreckem
 
unix training | unix training videos | unix course unix online training
unix training | unix training videos | unix course unix online training
Nancy Thomas
 
Fusion Middleware 11g How To Part 2
Fusion Middleware 11g How To Part 2
Dirk Nachbar
 
25 Apache Performance Tips
25 Apache Performance Tips
Monitis_Inc
 
Sql server troubleshooting
Sql server troubleshooting
Nathan Winters
 
KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
KeySens: Passive User Authentication Through Micro Behavior Modeling of Soft ...
Jiang Zhu
 
Linux MMAP & Ioremap introduction
Linux MMAP & Ioremap introduction
Gene Chang
 
Chapters 3 4
Chapters 3 4
sakshi_20
 
We Know Your Type
We Know Your Type
CTIN
 
Trouble shoot with linux syslog
Trouble shoot with linux syslog
ashok191
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
bokonen
 
UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1
Nihar Ranjan Paital
 
UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
Nihar Ranjan Paital
 
Karkha unix shell scritping
Karkha unix shell scritping
chockit88
 
Module 13 - Troubleshooting
Module 13 - Troubleshooting
T. J. Saotome
 
Advanced Oracle Troubleshooting
Advanced Oracle Troubleshooting
Hector Martinez
 
Linux troubleshooting tips
Linux troubleshooting tips
Bert Van Vreckem
 
unix training | unix training videos | unix course unix online training
unix training | unix training videos | unix course unix online training
Nancy Thomas
 
Fusion Middleware 11g How To Part 2
Fusion Middleware 11g How To Part 2
Dirk Nachbar
 
25 Apache Performance Tips
25 Apache Performance Tips
Monitis_Inc
 
Sql server troubleshooting
Sql server troubleshooting
Nathan Winters
 
Ad

Similar to Process monitoring in UNIX shell scripting (20)

Unit 10 investigating and managing
Unit 10 investigating and managing
root_fibo
 
linux_Commads
linux_Commads
tastedone
 
Linux 系統管理與安全:基本 Linux 系統知識
Linux 系統管理與安全:基本 Linux 系統知識
維泰 蔡
 
13 process management
13 process management
Shay Cohen
 
101 3.5 create, monitor and kill processes v2
101 3.5 create, monitor and kill processes v2
Acácio Oliveira
 
3.5 create, monitor and kill processes v2
3.5 create, monitor and kill processes v2
Acácio Oliveira
 
101 3.5 create, monitor and kill processes
101 3.5 create, monitor and kill processes
Acácio Oliveira
 
UNIX Notes
UNIX Notes
PandurangBiradar2
 
System Administration: Linux Process
System Administration: Linux Process
lucita cabral
 
2.1.using the shell
2.1.using the shell
donv214
 
578781849-RHSA-1-Chap578781850-RHSA-1-Chapter-4ter-7.pptx
578781849-RHSA-1-Chap578781850-RHSA-1-Chapter-4ter-7.pptx
AbdellahELMAMOUN
 
Linux system administration
Linux system administration
PoonamChawhan1
 
Managing Processes in Unix.pptx
Managing Processes in Unix.pptx
Harsha Patil
 
Managing Processes in Unix.pptx
Managing Processes in Unix.pptx
Harsha Patil
 
Resource Monitoring and management
Resource Monitoring and management
Duressa Teshome
 
Processes And Job Control
Processes And Job Control
ahmad bassiouny
 
Linux -5- system admin (sytem access and file system) .pptx
Linux -5- system admin (sytem access and file system) .pptx
SrujanKunta1
 
Process managment
Process managment
NaviyaMariya
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters
Acácio Oliveira
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters
Acácio Oliveira
 
Unit 10 investigating and managing
Unit 10 investigating and managing
root_fibo
 
linux_Commads
linux_Commads
tastedone
 
Linux 系統管理與安全:基本 Linux 系統知識
Linux 系統管理與安全:基本 Linux 系統知識
維泰 蔡
 
13 process management
13 process management
Shay Cohen
 
101 3.5 create, monitor and kill processes v2
101 3.5 create, monitor and kill processes v2
Acácio Oliveira
 
3.5 create, monitor and kill processes v2
3.5 create, monitor and kill processes v2
Acácio Oliveira
 
101 3.5 create, monitor and kill processes
101 3.5 create, monitor and kill processes
Acácio Oliveira
 
System Administration: Linux Process
System Administration: Linux Process
lucita cabral
 
2.1.using the shell
2.1.using the shell
donv214
 
578781849-RHSA-1-Chap578781850-RHSA-1-Chapter-4ter-7.pptx
578781849-RHSA-1-Chap578781850-RHSA-1-Chapter-4ter-7.pptx
AbdellahELMAMOUN
 
Linux system administration
Linux system administration
PoonamChawhan1
 
Managing Processes in Unix.pptx
Managing Processes in Unix.pptx
Harsha Patil
 
Managing Processes in Unix.pptx
Managing Processes in Unix.pptx
Harsha Patil
 
Resource Monitoring and management
Resource Monitoring and management
Duressa Teshome
 
Processes And Job Control
Processes And Job Control
ahmad bassiouny
 
Linux -5- system admin (sytem access and file system) .pptx
Linux -5- system admin (sytem access and file system) .pptx
SrujanKunta1
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters
Acácio Oliveira
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters
Acácio Oliveira
 
Ad

More from Dan Morrill (16)

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

Recently uploaded (20)

The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 

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