Linux self-healing script to check some process

2.2k Views Asked by At

Im new with Linux scripts, I need help to create one script with check some installed processes on a server and if one of these services is not running restart it, and recheck again those services and if there any error print it with echo as below :

dsisrv        (DSI service)                                  (7384)   Running
midaemon      (measurement interface)                        (1412)   Running
misrv         (measurement interface service)                (1384)   Running
perfalarm     (Alarm generator)                                       Stopped
perfalarmsrv  (Alarm generator service)                               Stopped
scopent       (data collector)                                        Stopped
scopesrv      (collector service)                                     Stopped
perfd         (Real Time Metric Access Daemon)               (7888)   Running
perfdsrv      (Real Time Metric Access Service)              (9020)   Running
ttd           (transaction tracking)                         (1808)   Running

in case any of above services is stopped, the script to run restart command.

Appreciate if any one help me to start with this script

Regards,

2

There are 2 best solutions below

0
On
#!/bin/sh
 SERVICE='httpd'
 if ps ax | grep -v grep | grep $SERVICE > /dev/null 
then
 echo "$SERVICE service running, everything is fine"
 else 
echo "$SERVICE is not running" echo "$SERVICE is not running!" | mail -s "$SERVICE down" root 
fi

Just add the service your looking for, this will mail you if the service goes down. Im assuming your using bash so enjoy.

0
On

i did simple script i hope this will be helpful please run this script as a root and add your services or daemons inside declaration array

declare -a service=(vsftpd sshd) 

full script

#!/bin/bash
declare -a service=(vsftpd sshd) ##declaration array
for x in ${service[@]} ##array with 
do
process=` ps -A | grep $x | awk '{print $4}' ` ### all process output
all_services=`echo $x`
line_no=` ps -A | sed -n '/'$all_services'/=' `
if ` ps -A | grep ${process[@]} > 0 ` ## condition to check if service available or not
then
echo "status running", " `ps -A | sed -n ''$line_no''p | awk ' {print $1 $4}'` "  ## service up running
else
service $all_services start ### start the daemon again
fi
done