How to reboot a Raspberry Pi when the WiFi is down

I'm sometimes unable to SSH into my Raspberry Pi. I'm not sure why. I think it might help if I make a simple script that will reboot the Raspberry Pi when it can't ping Google. The script below is the solution I came up with. It pings Google every two minutes and reboots if it doesn't get a response.

Prepare log files

We'll write the date and time of any reboots to ~/reboots.log. We'll write all other logs to ~/rebootOnNetworkOutage.log.

touch ~/reboots.log
touch ~/rebootOnNetworkOutage.log

Script to reboot on network outage

This script pings Google. If it doesn't get a response, then it reboots the system. (Make sure to run chmod +x ~/rebootOnNetworkOutage.sh to make it executable.)

# ~/rebootOnNetworkOutage.sh

echo ""
echo "***** ***** *****"
echo "***** ***** *****"
echo "***** ***** *****"
echo ""
echo `date`
echo ""
# Delete the log if it's bigger than 1 MB
find /home/pi/rebootOnNetworkOutage.log -size +1M -delete
# Ping Google. If the ping fails, log the current date
# and time to ~/reboots.log and reboot the system.
ping www.google.com -c 1 || ( echo `date` >> /home/pi/reboots.log && echo "rebooting!" && /sbin/shutdown -r now )

Run script every minute

We can add the script to the end of the general crontab file to be run by root every two minutes. We need root permissions in order for reboots to work.

# /etc/crontab

...

*/2 * * * *       root    /home/pi/rebootOnNetworkOutage.sh >> /home/pi/rebootOnNetworkOutage.log