Services Monitor Cronjob for Linux

After searching for several hours for a decent direct explanation of how to Monitor or automate a script to check for critical service that’s run on Linux Box, which is Ubuntu in my case, I’ve decided to post a little help for Linux Administrators out there.

So, you really need to study the service you’ll be monitoring on your box, how much crucial is it to wait until it gets fixed, then do the following:
1) You need SU access such as ‘root’.
2) Create a Shell Script, for example chkservice.sh under the folder /opt or any other folder you like.
3) Use this code:

STATUS=`/sbin/pidof SERVICE_NAME`
if [ $STATUS > 0 ]
then
exit 0
else
echo “Service SERVICE_NAME started.”
/sbin/service SERVICE_NAME start
exit 0
fi

 4) Replace SERVICE_NAME with the service you aiming to Monitor, for example one my Ubuntu Servers I had a problem with ‘nginx’ which a mini webserver from Apache.

5) You can repeat the code above in the same file for other services.

6) Add the Shell Script to your Crontab depending on your own frequency, for example I had to check this for every 5 minutes, so the cronjob should be:

*/5 * * * * * /opt/chkservice.sh

6) The cronjob will email the Server Admin the output result, incase of any issues.

Please feel free to contribute, feedback is very much appreciated.