Basic Bash Scripting: monitor critical systemd services

 This is a little script that I wrote to monitor Postfix, but could apply to any other systemd service.

[root@server ~]# cat /root/bin/PostfixChecker.sh

#!/bin/bash

systemctl status postfix > /dev/null 2>&1

if [ $? -ne 0 ]

then

logger "PostfixChecker: Postfix is dead! restarting via systemctl."

systemctl restart postfix

fi

I call this script periodically using cron every 10 minutes:

[root@server ~]# crontab -l

[output omitted...]

*/10 * * * * /root/bin/PostfixChecker.sh

The command "systemctl status postfix" returns 0 only if the service is up and running, which is why we check the return value (using the bash variable $?). If it is not equal to zero (-ne means not equal) then we log a message to the system logger and restart the service. 

Comments