Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save projectivemotion/741af56867ec577ef9edfb3f1c188935 to your computer and use it in GitHub Desktop.
Save projectivemotion/741af56867ec577ef9edfb3f1c188935 to your computer and use it in GitHub Desktop.
Trigger a systemd service when a host becomes unreachable via ping. Machine can be hostname or ip address.
#!/bin/sh
# add to your crontab?
# 45 * * * * /path/to/start-service-if-host-unreachable.sh
machine="moto"
service="reverse-tunnel"
if [ "$USER" != "root" ] ; then
echo "You are not root. bye."
exit 1;
fi
is_started () {
systemctl status $service
[ $? -eq 0 ] && return 0 # 0 indicates that service isrunning
return 1
}
ping -c 1 "$machine"
if [ $? -eq 0 ] ; then # if true, indicates machine is online
if is_started ; then # 0 indicates service is running
echo "Service is running.. stopping now."
systemctl stop $service
fi
exit 0
fi
echo $machine did not respond to ping.. starting service..
# start tunnel
is_started || systemctl start "$service"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment