I was really surprised after a failure of the wireless router in my house, that the pi didn’t reconnect. Looking around I don’t seem to be the only person having this issue so I modified a script I found online and have cron run it periodically so have the system reconnect.
I think the original script tried to ping the Google DNS (8.8.8.8) IP but, where I live, the internet connection is completely unreliable so this would fail often. My script just checks that it can get to the router, and if it can’t, then it restarts the network.
The script is should live in /usr/local/bin/wifi_rebooter.sh.
#!/bin/bash
INTERFACE=wlan0
GATEWAY=$(route -n | grep '^0' | grep UG | awk '{print $2}')
# Only send two pings, sending output to /dev/null
ping -c2 ${GATEWAY} > /dev/null
# If the return code from ping ($?) is not 0 (meaning there was an error)
if [ $? != 0 ]
then
# Restart the wireless interface
ifdown --force $INTERFACE
ifup $INTERFACE
fi
Make sure it’s executable and run it from cron. The line should looks something like this:
*/5 * * * * root /usr/local/bin/wifi_rebooter.sh