Bash script to monitor system service

This bash script runs and checks to see if a service like httpd, or mysql is running and alerts if it is not.

Script Usage

servicemonitor.sh httpd mariadb

Where httpd and mariadb are the services you want to monitor/check.

Setup Script

Create servicemonitor.sh file and paste the following contents in.

#!/bin/bash

timeHour=`date +%H` # date/time just shows the hour
quietHour="02"    # If it is this hour, then exit program, useful if services are expected to go down during a particular time for maintenance
if ( echo ${timeHour} | grep ${quietHour}); then
         echo "Is during quiet time.  Quiting."
         exit
fi

 function ALERT {
 msg="~/teams.sh -b"  # Sends a message to Microsoft Teams channel.  Needs the teams.sh script in the users home directory.
 ${msg} "$1"
 }
 function SERVICECHECK {
 serviceName="${1}"
 if (systemctl status ${serviceName} | grep Active | grep inactive); then
         ALERT "ERROR: $(hostname) - ${serviceName} - ${0} is inactive"
         echo "ERROR: ${serviceName} is inactive!"
 else
         echo "Running!"
 fi
 }
 for i in $@
 do
 echo Checking ${i}
 SERVICECHECK ${i}
 done

Note the teams.sh script that is called is another script that is called that sends an alert to Microsoft Teams. Is not needed for this script to run, but allows for remote alerting.

Save file and make it executable

chmod +x servicemonitor.sh

Add script to crontab (Optional)

crontab -e

The following runs the script every 5 minutes. Can change the 5 to 1 to run every minute. Change httpd and mariadb to the service you want to monitor.

*/5 * * * * /home/UserName/servicemonitor.sh httpd mariadb

Leave a Reply

Your email address will not be published. Required fields are marked *