Pages

Thursday, November 14, 2013

How to find service is running or dead in Linux,Shell Script

       In unix based machine having shell script support,how will you find a particular service name,whether it is running or dead?and if dead how to autostart it?I have one small shell script written in Bash.You can utilize it is korn shell(ksh),sh shell as well by updating first line of script file.i.e #!/bin/bash
       Script is made like that it will ask you to enter exact service name,It will find service is exist or not,if not then it will ask you to start service again,by again entering service name again,and it will start it automatically ,and will make it persistant on restart of linux machine.





/* #################Script Start################# */

#!/bin/bash
/usr/bin/read -p "Enter Service  Name You Want To Check,Please enter exact service name e.g. smb,ntpd,httpd etc..." pid_name
/bin/echo "You have Entered Process Name $pid_name"
/bin/echo " Please Wait..."
k=$pid_name
if [ -f /var/run/$pid_name.pid ];
then
/bin/echo " Process_name $pid_name is running "
else
/bin/echo " Process_name $pid_name is dead or not running "
/bin/echo " Do you want to start dead service?"
/bin/echo " As you are on linux machine,we are expacting you to enter exact process name :) "
/bin/echo " Please enter Process exact name again,else press ctrl + c "
read $k
/etc/init.d/$k restart ;chkconfig $k on
fi

/* ################Script End################# */

To Download This Check_Service Script Click Here

         You can put this script as a cronjob(schedule auto check) that will check particular service every 30 minutes automatically everyday.For this you will need to configure crond services.You can follow below steps to do:
          Before you do with cronjob,you will need to modify script according to mentioned below,i have decided to check mysqld service ,and if it is dead then it will autostart it:


(1)service crond start
(2)crontab -l (To list the cronjobs)
(3)su - (login with superuser)
(4)crontab -e (add new cronjob)
(5)*/30 * * * * /user/bin/sh /path/of/script/service_autocheck.sh
(6)save file by :wq!
(7)service crond restart
(8)chkconfig crond on

Shell Script Code