Skip to content

Instantly share code, notes, and snippets.

@briantissue
Last active January 3, 2019 14:11
Show Gist options
  • Save briantissue/1764ab00b17640063c0f028083a5f636 to your computer and use it in GitHub Desktop.
Save briantissue/1764ab00b17640063c0f028083a5f636 to your computer and use it in GitHub Desktop.
Monitor a web server as a system daemon; Send notification on Down and when the site comes up
#!/bin/bash
[email protected]
[email protected]
SERVER=https://servertomonitor.domain.com
PAUSE=300 # Checks this server every 5 minutes
FAILED=0
DEBUG=0
while true
do
/usr/bin/curl -fsSk -m 10 $SERVER > /dev/null 2>&1 # This includes a webserver timeout of 10 seconds it'll alarm
CS=$?
# For debugging purposes
if [ $DEBUG -eq 1 ]
then
echo "STATUS = $CS"
echo "FAILED = $FAILED"
if [ $CS -ne 0 ]
then
echo "$SERVER is down"
elif [ $CS -eq 0 ]
then
echo "$SERVER is up"
fi
fi
# If the server is down and no alert is sent - alert
if [ $CS -ne 0 ] && [ $FAILED -eq 0 ]
then
FAILED=1
if [ $DEBUG -eq 1 ]
then
echo "$SERVER failed"
fi
if [ $DEBUG = 0 ]
then
echo "$SERVER went down $(date)" | mutt -s "$SERVER went down" "$NOTIFYEMAIL"
fi
# If the server is back up and no alert is sent - alert
elif [ $CS -eq 0 ] && [ $FAILED -eq 1 ]
then
FAILED=0
if [ $DEBUG -eq 1 ]
then
echo "$SERVER is back up"
fi
if [ $DEBUG = 0 ]
then
echo "$SERVER is back up $(date)" | mutt -s "$SERVER is back up again" "$NOTIFYEMAIL"
fi
fi
sleep $PAUSE
done
@briantissue
Copy link
Author

Place above script in /usr/local/bin

Place the following in a file (servercheck-name.service) at /etc/systemd/system
/-------------------------------------------/
[Unit]
After=network.target

[Service]
ExecStart=/usr/local/bin/monitor-website-systemdaemon.sh

[Install]
WantedBy=default.target
/-------------------------------------------/

After both files are placed:
systemctl enable servercheck-name.service
systemctl start servercheck-name.service
systemctl status servercheck-name.service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment