Service Check

This script is to check if a service is running. If not, restart it and send an email.

First of make a file and give it “execute” permission:

touch check_service.sh
chmod +x check_service.sh

Now edit the file with the following script:

 #!/bin/bash
 
 ### edit the following ###
 service=service_name
 [email protected]
 ### stop editing ###
 
 host=`hostname -f`
 if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
 then
 echo "$service is running"
 else
 /etc/init.d/$service restart
 if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
 then
 subject="$service at $host has been started"
 echo "$service at $host wasn't running and has been started" | mail -s "$subject" $email
 else
 subject="$service at $host is not running"
 echo "$service at $host is stopped and cannot be started!!!" | mail -s "$subject" $email
 fi
 fi
 

The go ahead and create a Cron job to run periodically (you can use this to simplify your life: cron.help).

This is an example to run this script every day at 01:00:


0 1 * * * /home/username/scripts/check_service.sh