Raspberry Pi Endeavors – Networking restart script

After popping to Maplin today to buy some electrical components to connect up to my Pi, I decided to write a script to reconnect my Pi to the internet if its WiFi connection fails, which it seems to do fairly regularly, and I haven’t nailed down completely whats causing the USB Belkin adapter to stop working.

Basically, my script pings Google, if it gets a response – great. If not, try once more, and if no luck, restart the networking service. If still no luck, pull down and put back up again the wlan0 (wireless lan) adapter.

Script is below if you wish to nick it. Also I modified my /etc/resolf.conf to match the one on Adafruit’s Pi learning site, whose tutorials I am following.

Matt

Code [click here to download the properly indented version]:

#!/usr/bin/python
import commands

def can_ping_google():
ping_once = “ping www.google.co.uk -c 1″
output = commands.getstatusoutput(ping_once)
if output[1] == ‘ping: unknown host www.google.co.uk’:
print “Ping failed”
return False
else:
return True

def connection_test():
if can_ping_google():
print “Pinged fine”
return
else:
if can_ping_google():
print “Pinged fine second time, first was a fail”
return
else:
print “Restarting networking service”
restart_output = commands.getstatusoutput(“sudo service networking restart”)
print restart_output
if can_ping_google():
print “Restarting worked, can ping now”
return
else:
print “Restarting didn’t work. Will force wlan0 down and up, and restart networking after”
print commands.getstatusoutput(“sudo ifdown –force wlan0″)
print commands.getstatusoutput(“sudo ifup wlan0″)
print commands.getstatusoutput(“sudo service networking restart”)
if can_ping_google():
print “Down, up and restart worked. Can ping.”
return
else:
print “Couldn’t ping Google after up, down and restarting.”

connection_test()