Ubuntu: Script to Check Internet Connection and Repair

  • Posted August 22, 2014. Last modified March 23, 2017 by

At school there are a set of laptops which I occasionally run experiments on for my research. I usually like to work remotely as I travel a bit and live in other cities. These laptops are all connected to the university network through a wireless AP in my office which passes the DHCP requests to somewhere in the department. This lets each one get an external IP which is extremely useful for SSH-ing into the machines one at a time remotely. However sometimes, for unknown reasons the IPs revert back to 10.x.x.x addresses and aren’t reachable. The problem can be solved by releasing the old address a couple of times:

sudo dhclient -r wlan1
sudo dhclient -r wlan1

and then asking for a new address:

sudo dhclient wlan1

However, this isn’t too helpful if I’m out of the lab. So to automate this I came up with this script which can be turned into a cronjob:

ping -w 1 -c 5 -q www.google.ca > /dev/null
status=$?

if [[ $status == 1 ]]; then
echo “Connection Alive”
else
echo “Connection Dead. Trying to Renew IP”;
sudo dhclient -r wlan1
sudo dhclient -r wlan1
sudo dhclient wlan1
echo “Done”;
fi

There’s probably better ways to check if the connection is up and working, but this does the job. Originally I tried an IP address (for example 8.8.8.8), but unfortunately when there is a local 10.x.x.x connection the ping will make it through, but name resolution does not work. This is why I hardcode the www.google.ca location into the script – so that it forces a name resolution and then fails.

You can then add this line to your crontab:
20 * * * * /scripts/ping-test.sh

Leave a Reply

Your email address will not be published. Required fields are marked *