Post

Linux - Check Services

Linux - Check Services

This script is to check if a service is running. If not, restarts the service and send an email to a specific recipient.

Preparing the script

First of make an executable bash script:

1
2
touch check_service.sh
chmod +x check_service.sh

Now edit the file with the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #!/bin/bash
 
 #---- edit the following ----#
 service="service_name"
 email="[email protected]"
 #------- stop editing -------#
 
 host=`hostname -f`
 if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
 then
 echo "$service is running"

 else
 /etc/init.d/$service restart

 if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
 then
 subject="$service at $host has been started"
 echo "$service at $host wasn't running and has been started" | mail -s "$subject" $email

 else
 subject="$service at $host is not running"
 echo "$service at $host is stopped and cannot be started!!!" | mail -s "$subject" $email

 fi
 fi

Scheduling

The go ahead and create a cron job to run periodically.

You can use the following site to quickly configure a cronjob: cron.help.

This is an example to run this script every day at 01:00:

1
0 1 * * * /home/harry.vasanth/scripts/check_service.sh
This post is licensed under CC BY 4.0 by the author.