How to make the Raspberry Pi automatically restart the WiFi interface

My WiFi router sometimes goes haywire and the Pi won’t notice when the WiFi connection is up again. So I wrote this little script:

#!/bin/bash                                   

TESTIP=192.168.1.1

ping -c4 ${TESTIP} > /dev/null

if [ $? != 0 ]
then
logger -t $0 "WiFi seems down, restarting"
ifdown --force wlan0
ifup wlan0
else
logger -t $0 "WiFi seems up."
fi

You can put this script under /usr/local/bin and add the following line to the system wide /etc/crontab:

*/5 * * * * root /usr/local/bin/testwifi.sh

This will check every five minutes if the connection is still up, and restart it, if the router cannot be pinged. If you dislike all the syslog messages, you can comment them out in the script.
My corresponding /etc/network/interfaces looks like this (I uninstalled all the network managers):


auto lo

iface lo inet loopback
iface eth0 inet static
address 192.168.3.42
netmask 255.255.255.0

auto wlan0
iface wlan0 inet dhcp
pre-up wpa_supplicant -Dwext -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf -B
post-down killall wpa_supplicant ; rmmod 8192cu ; modprobe 8192cu

iface default inet dhcp

The wpa_supplicant.conf should be easy to generate, there are lots of guides on the web for this.

4 thoughts on “How to make the Raspberry Pi automatically restart the WiFi interface”

  1. Great idea. Thank you.

    I am using my Raspberry PI at home and work so the 192.168.1.1 IP address is changing everytime. So I have changed the TESTIP to google.com 🙂

Leave a Reply

Your email address will not be published.