Many of you may have think of how to keep essential services running during your server is up. Here is a simple shell script I just write and would like to share with you. Please let me know if there is any bug.
Please note the below bug fix version if you ever visit here. This version was tested and found working.
To use this script, you have to make an entry in the /etc/crontab as below.
# Check if essential services are running every 5 minutes and restart if not
*/5 * * * * root /usr/bin/cksrv.sh
Remember to make the script runnable by : chmod 770
File name : cksrv.sh
Code: Select all
#!/bin/bash
# File : /usr/bin/cksrv.sh (Version 1.1)
# Last update : 28 Dec 2017
# Copyright : GPL Licence Version 2 or above
# Bash shell script to test processes or services and then act on
# Super user right is required for running this shell script file.
# Array of services
srvary=( "nmb" "smb" "sshd" )
# Function to log failed service(s) with date and time
function logsrvstat()
{
# Parameter srvstatcode & srvname are passed to this function
# Create the log file by command : touch /yourpath/failsrv.log if needed.
if [ "$srvstatcode" -eq 1 ]; then
date +"%Y-%m-%d %H:%M:%S" >> /usr/bin/failsrv.log
echo $srvname service "is not enabled! Enable it again..." >> /usr/bin/failsrv.log
elif [ "$srvstatcode" -eq 2 ]; then
date +"%Y-%m-%d %H:%M:%S" >> /usr/bin/failsrv.log
echo $srvname service "is not running! Restarting..." >> /usr/bin/failsrv.log
fi
}
for i in "${srvary[@]}"
do
systemctl is-enabled $i.service > /dev/null
if [ $? -gt 0 ]; then
systemctl enable $i.service
srvstatcode=1
srvname=$i
logsrvstat srvstatcode srvname
fi
systemctl is-active $i.service > /dev/null
if [ $? -gt 0 ]; then
systemctl restart $i.service
srvstatcode=2
srvname=$i
logsrvstat srvstatcode srvname
fi
done