Check service is running with systemctl and start it if stopped + mail

Check service is running with systemctl and start it if stopped + mail

I did an earlier version of this script on Fedora 16 but used pidof rather than systemctl to check a services status. I use this script below on a few fedora 17 boxes and it seems to be working very nicely :) Any suggestions or feedback is as always much appreciated.

This script can go anywhere but make sure its executable. I chose /usr/bin/SCheck

#!/bin/bash
# Simple script that uses systemctl to check if a service is
# running. If its not it is restarted and an email is sent to
# the configured mailbox.
#
# http://wp.me/p25Sys-c0 
# m00nie
######################

# The service we want to check (according to systemctl)
SERVICE=openvpn@smileytown.service
# Where to send the restart mail to
MAILBOX=spam@m00nie.com

if [ "`systemctl is-active $SERVICE`" != "active" ] 
then 
	echo "$SERVICE wasnt running so attempting restart"
	systemctl restart $SERVICE
	echo "Mailing $MAILBOX with current status"
	systemctl status $SERVICE | mail -s "$SERVICE was restarted" $MAILBOX
	exit 0
fi 
echo "$SERVICE is currently running"
exit 0

Next simply add a crontab entry to run the script as often as you like. I run the script every 5 minutes.

# Check OpenVPN is running
*/15 * * * * /usr/bin/SCheck > /dev/null

Now every 15 minutes the script should run, check the service is running and if not restart it for you. You will only be mailed when it has been restarted.

m00nie :D