Ubuntu – Auto reconnect to wifi once disconnected

Ubuntuusbwifi

On Ubuntu 14.04, I am using a USB wireless adapter to connect to a wireless network. The connection is often disconnected (I have tried to solve the problem, but I don't know why. That is another question. See the output of dmesg | grep wlan here).

My Network Manager sometimes can automatically reconnect, but sometimes it can't.

So when it disconnects, I often have to run

sudo dhclient -v wlan1

to reconnect. If that doesn't work, I will run

sudo wpa_supplicant -B  -i wlan1 -c /etc/wpa_supplicant.conf
sudo dhclient -v wlan1

If that doesn't work, I will also reload its driver rt2800usb first:

sudo modprobe -r rt2800usb
sudo modprobe rt2800usb
sudo wpa_supplicant -B  -i wlan1 -c /etc/wpa_supplicant.conf
sudo dhclient -v wlan1

How shall we automatically run the commands every time it disconnects, i.e. make re-connection automatic?

There is a problem that mostly the logic name for my USB adapter is wlan1 but sometimes is wlan0.

Best Answer

You can get the state of wlan1 from /sys/class/net/wlan1/carrier , this is a sample script to check the state of your wifi interface every 2 seconds , then reconnecting ( replace sleep 2 to check the connectivity every n seconds):

while true
     do
     i=$(cat /sys/class/net/wlan1/carrier)
if [ $i == 1 ]
then
       echo "connected"

else
       echo "reconnecting"
       killall wpa_supplicant
       modprobe -rv rt2800usb
       modprobe -v rt2800usb
       wpa_supplicant -i wlan1 -c/etc/wpa_supplicant.conf -B
       dhclient wlan1
       echo "reconnected successfully"
       fi
sleep 2
done

testing the script

Run this script then open a new terminal and run killall wpa_supplicant, you will be reconnected again.

Related Question