Friday, September 4, 2015

Simple process monitoring script with email alerting

If you don't have or don't want to install additional software for system/application monitoring (like Nagios, Zabbix, Munin, Big Brother, etc.) you may use this simple script:


#!/bin/bash

MAIL="your@email.address"
PROGRAM="httpd"
HOST=$(uname -n)
DATE=$(date)
TMPFILE=/var/tmp/monitor-$(PROGRAM).lock

OUTPUT=$(ps -ef | grep -c "$PROGRAM")
if [ $OUTPUT -eq 1 ]; then

  if [ -f $TMPFILE ]; then
    echo "Lock file exists"
  else
    echo "$DATE $HOST program \"$PROGRAM\" is not running" | mailx -s "\"$PROGRAM\" is not running on $HOST" $MAIL
    touch $TMPFILE

  fi
fi


In PROGRAM variable put the name of the process that you expect to be running, make sure that the monitoring script name will not contain the same string.
Basically, if the program is running "ps -ef | grep program" will return 2 or more rows (one with the program itself and the second one with "grep program").
Otherwise it will only return one row ("grep program") which will trigger the alert and you will get an email.
By creating TMPFILE script will avoid bothering you again and again about the same issue.
Make sure to remove that file after you restart monitored process.

Once the script is ready save it and add to cron, i.e.:
$ crontab -e
* * * * * /path/to/the/script > /dev/null 2>&1




No comments:

Post a Comment