Linux service restart shell script

 

I badly needed a script that would check if my running services (in this script it'll check varnish and apache2 services) are alive- if not, it'll restart the dead service and write a log.
Pretty handy!
#!/bin/sh


STARTAPACHE="/etc/init.d/apache2 start"

STARTVARNISH="/etc/init.d/varnish start"

LOGFILE=/var/log/service_uptime.log

################ Check Varnish #################

SERVICE='varnish'

echo "" >> $LOGFILE

echo `date` >> $LOGFILE

if ps ax | grep -v grep | grep $SERVICE > /dev/null

then

echo "$SERVICE service running, everything is OK" >> $LOGFILE

else

echo "$SERVICE is not running, restarting $SERVICE" >> $LOGFILE

checkvarnish=`ps ax | grep -v grep | grep -c varnish`

if [ $checkvarnish -le 0 ]

then

$STARTVARNISH

if ps ax | grep -v grep | grep $SERVICE > /dev/null

then

echo "$SERVICE service is now restarted, everything is OK" >> $LOGFILE

fi

fi

fi

############### Check Apache ################

SERVICE='apache2'

if ps ax | grep -v grep | grep $SERVICE > /dev/null

then

echo "$SERVICE service running, everything is OK" >> $LOGFILE

else

echo "$SERVICE is not running, restarting $SERVICE" >> $LOGFILE

checkapache=`ps ax | grep -v grep | grep -c apache2`

if [ $checkapache -le 0 ]

then

$STARTAPACHE

if ps ax | grep -v grep | grep $SERVICE > /dev/null

then

echo "$SERVICE service is now restarted, everything is OK" >> $LOGFILE

fi

fi

fi

exit 0

Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.