Automatically Reconnect WiFi Connection If The Connection Is Lost
Published October 9th, 2015 at 10:58 AM. by Joe Prochazka
There has been occasions when either a WiFi router would hiccup or a wireless adapter would lose connection to the WiFi network causing connectivity between the machine and the WiFi network to be lost. The following script can be put in place in order to check if in fact the WiFi adapter is up and running as well as connected to the network. If in fact the wireless adapter is not connected anymore the script will attempt to bring the wireless connection back up until it is once again connected.
First off we will need to create a new file which will be /root/wifimonitor.sh.
sudo nano /root/wifimonitor.sh
Now that the file is open in your text editor add the following text to this file. Be sure to specify the WiFi interface which you wish to monitor. By default if only one WiFi adapter is present the interface should be named wlan0. If you are not sure of the interfaces name running the command ifconfig will list all network devices installed of which you can choose the correct one.
!/bin/bash
# Name of the interface to monitor.
INTERFACE="wlan0"
while [ true ]; do
if ifconfig ${INTERFACE} | grep -q "inet addr:"; then
sleep 60
else
echo "[" + $(date +%t) + "] WiFi connection appears to be down: Attempting to reconnect to network."
ifup --force ${INTERFACE}
sleep 10
fi
done
Next you will need to make the newly created bash script executable by running the following command.
sudo chmod +x /root/wifimonitor.sh
We will want to have this script started after each reboot of the machine so we will need to open the file /etc/rc.local and make a quick addition to it.
sudo nano /etc/rc.local
Add the following line directly above the line "exit 0" which should be located near the end of the file.
/root/wifimonitor.sh &
If you wish to log the output of the script for trouble shooting purposes you can use the following line instead. This will log any attempts to bring the down interface up to the file /var/log/wifimonitor.log.
/root/wifimonitor.sh > /var/log/wifimonitor.log &
Instead of rebooting the machine to start the monitoring script we will simply execute the script for now using the following command.
sudo /root/wifimonitor.sh &
Again if you decide to log attempts to bring a down interface back up use the following line instead to start the script.
/root/wifimonitor.sh > /var/log/wifimonitor.log &