I will give an example of a simple script for restarting services if they are not running and sending a notification by email:
#!/bin/bash
SERVICES="ssh apache2 zabbix-server zabbix-agent mysql smbd nmbd asterisk"
DATE=$(date '+%d-%m-%Y %H:%M:%S')
for SERVICE in ${SERVICES}
do
service $SERVICE status 2>&1>/dev/null
if [ $? -ne 0 ];
then
service $SERVICE stop
sleep 3
service $SERVICE start
echo -e "Starting $SERVICE"
(echo "Subject:Restarting $SERVICE"; echo "$DATE $SERVICE is not running on $HOSTNAME! Restarting!";) | sendmail test@ixnfo.com
else
echo -e "$SERVICE OK"
fi
done
In the script, specify the email on which you want to receive notifications, and in the “SERVICES” list of services through the space that you want to check.
I first stopped the service in order to surely stop all possible processes, paused for 3 seconds and then started, because with the restart command, some highly loaded services could not start correctly and hang with the status “active (exited)”.
To make the script automatically run for example every 10 minutes, add a line to /etc/crontab:
*/10 * * * * root /dir/watchdog.sh > /dev/null 2>&1
See also my articles:
Installing and Configuring Postfix
Using and configuring CRON
Installing and Configuring Monit