Skip to content

Instantly share code, notes, and snippets.

@farshidtz
Last active July 18, 2020 09:56
Show Gist options
  • Save farshidtz/e6e378dc6b41dc8edb70478ade29e7e9 to your computer and use it in GitHub Desktop.
Save farshidtz/e6e378dc6b41dc8edb70478ade29e7e9 to your computer and use it in GitHub Desktop.
A watchdog script to monitor the network connectivity (ping status) and reboot when there is no connection
# A watchdog script to monitor the ping status and reboot the device
# when there is no connection after a specified number of tries.
#!/bin/sh
echo '\nStarted watchdog script.'
address=8.8.8.8 # or a local gateway address
max=5 # number of retries before reboot
interval=120 # seconds between each retry
verbose=false # set to true to print also the success logs
counter=0
while true; do
now=$(date --rfc-3339=seconds)
# check connection to address
# -q quiet
# -c nb of pings to perform
ping -q -c1 ${address} > /dev/null
if [ $? -ne 0 ]
then
counter=$((counter+1))
printf '%s -- %s -- Failed to ping %d\n' "$now" $address $counter
else
counter=0
$verbose && printf '%s -- %s -- OK\n' "$now" $address
fi
# if $max consecutive pings fail
if [ "$counter" -eq "$max" ]
then
# reboot the device
echo "Rebooting..."
reboot
fi
sleep $interval
done
## To start after reboot, e.g. using Crontab (make sure the logs are rotated):
# sudo crontab -e
## Add:
# @reboot sh /home/pi/watchdog-network.sh >> /var/log/watchdog-network.log 2>&1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment