Linux / Unix Script: Simple Process Checker To Find Out If A Service Is Running or Not

by on March 13, 2013 · 0 comments

A simple shell script to find out whether critical services are running or, not under Linux or Unix operating systems. The script can send notification using email.

  1. #!/bin/bash
  2. # Name : service.chk
  3. # URL: http://bash.cyberciti.biz/monitoring/simple-process-checker-script/
  4. # Purpose: A simple process checker. Find out if service is running or not.
  5. # Tested on: Debian and RHEL based system only.
  6. # ----------------------------------------------------------------------------
  7. # Author: nixCraft <http://www.cyberciti.biz>
  8. # Copyright: 2009 nixCraft under GNU GPL v2.0+
  9. # ----------------------------------------------------------------------------
  10. # Last updated: 13/Mar/2013 - Added support for email and other enhancements
  11. # Last updated: 05/Dec/2011 - Added support for binary path check
  12. # ----------------------------------------------------------------------------
  13.  
  14. ## Change as per your distro
  15. _pgrep="/usr/bin/pgrep"
  16. _mail="/usr/bin/mail"
  17.  
  18. ## Add binary list here
  19. _chklist="/usr/bin/php-cgi /usr/sbin/nginx /usr/sbin/lighttpd /usr/sbin/mysqld /usr/sbin/apache2 /usr/sbin/named /usr/sbin/pgsqld"
  20.  
  21. ## yes | no
  22. _sendemail="no"
  23.  
  24. ## Add your email id
  25. _email="your@mobile.email.id.example.com"
  26.  
  27. ## Do not change below
  28. _failed="false"
  29. _service="Service:"
  30.  
  31. _running() {
  32. local p="${1##*/}"
  33. local s="true"
  34. $_pgrep "${p}" >/dev/null || { s="false"; _failed="true"; _service="${_service} $1,"; }
  35. [[ "$s" == "true" ]] && echo "$1 running" || { echo -n "$1 not running"; [[ ! -f "$1" ]] && echo " [ $1 not found ]" || echo ; }
  36. }
  37.  
  38. ## header
  39. echo "Service status on ${HOSTNAME} @ $(date)"
  40. echo "------------------------------------------------------"
  41.  
  42. ## Check if your service is running or not
  43. for s in $_chklist
  44. do
  45. _running "$s"
  46. done
  47.  
  48. ## Send a quick email update (good for cron jobs) ##
  49. [[ "$_failed" == "true" && "$_sendemail" == "yes" ]] && { _mess="$_service failed on $HOSTNAME @ $(date)";
  50. $_mail -s 'Service not found' "$_email" < "${_mess}";
  51. }
  52.  

Sample outputs:

Fig.01: Script in action (click to enlarge)

Fig.01: Script in action (click to enlarge)



4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

Previous Script:

Next Script: