Sunday, August 12, 2007

checking daemon service bash script

How to restart daemon service if found not running?
How to check for service at regular time interval?
How to send notification from terminal?
How to find PID of daemon?
How to have a heartbeat-like checking of service?
How to create a script that checks for linux service?

This blog entry serves as a basic start for creating bash shell scripts that checks daemonized linux service regularly.

A real quick bash script on how to check postfix and sendmail daemon service every 5 minutes.

The below example checks sendmail damon service as an example. All lines that start with # character are bash comments for clarity.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! /bin/bash
PATH=$PATH:/usr/bin:/bin

# fetch system date below
date=`date "+%A %m-%d-%Y %r"`

# we use pidof to get the daemon PID
# we use awk to get the first child PID only for possible daemon children thread
ayos=`/sbin/pidof sendmail | awk '{ print $1}'`

# if PID has a value greater than 0 then the service is alive then
if [ $ayos > 0 ] ; then
# everything is OK
echo service is alive
exit 0
fi

# goes here if there is no existing PIDs, thus we need to restart it
# and sends email notification to admins
if [ $ayos = 0 ]; then
echo Dead, starting sendmail daemon service now...
# SERVICE RESTARTS SHOULD COME FIRST BEFORE SENDING OUT ANY EMAIL NOTIFICATIONS
# (thx to srineer)
/sbin/service sendmail restart
echo "Restarted at $date" | mail -s "sendmail from server restarted" youremail@yourdomain.com
fi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can execute this script from command line or from crontab jobs. Crontab jobs sample can be from this link. Adding it to crontab jobs like so

# */5 * * * * /root/myscripts/check_service.sh > /dev/null 2>&1

Make sure the scripts is root executable like so

# chmod 700 check_service.sh

and you're good to go.

Alternatively, this can modified further to fit other daemon services like postfix, dovecot, apache, mysql, spamassassin, mailscanner, antivirus, bind DNS, radius, and other daemon services that make use of PIDs!

HTH

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy