Shell Script to Check Running Services in Linux.

Most networks rely on services to run all the time, whether it is MySQL for database, or Apache for web services, the fact of the matter is that those services need to be available all the time; therefore, admins need to make sure those services are running. So here’s a simple, yet efficient script that checks whether a service is running, and if it’s not, it tries to restart the service 3 times, if it fails to start the service; then, it proceeds to notify the user by emailing the log file. You can change the “service” variable to suit your needs depending on the service. Also, you could add more services and use a “for” loop to iterate through every single service. This script kind of creates a starting point.

#!/bin/bash
#author: jorge L. Vazquez
#purpose: checking running services
 
email=root
service=apache2
count=0
threshold=2
servicelog=/var/log/$service.log
 
#checking if service is running
ps -e | grep $service > /dev/null
servicestat=$(echo $?)
 
#if service not running lets try restart 3 times
if [ "$servicestat" != 0 ]; then 
 
	while [ "$count" -le "$threshold" ]
	do
		#attempt to start the service
		/etc/init.d/$service start >> $servicelog 2>&1
		if [ $? != 0 ]; then
			((count=count+1))
		else
			exit 0  #if service started exit
		fi
	done
	#if service could not be started, notify
	cat $servicelog | mail -s "problem starting $service" $email 2>/dev/null
fi
 
#END
Share This!

Leave a Reply

Your email address will not be published.