Ubuntu: Script to Check Internet Connection and Repair

#automatic #interface #ip address #linux #miscellaneous #repair #ubuntu #wireless networks

 

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

Comments (0)


Leave a Comment

Log in to leave a comment.

Most Recent Post

Building a Better GitHub Stats Card

I've had a GitHub profile stats card for a while now, but I was never fully happy with it. The existing tools each had trade-offs that bugged me, so I ended up building my own by combining the best parts of three different projects. Here's how it went. The Problem There are a few popular projects fo...