Many of our Raspberry Pi projects needs remote accessibility. This means you spends lot of time using either VNC or SSH to access the Raspberry Pi. Unfortunately, when wifi connectivity drops and failed to re-connect your whole world stops right? On such situations, physically accessing the RPi and doing the restart is really a pain.
You can just copy paste this script into "/usr/local/bin/checkwifi.sh"
What we are trying to do is, we are restarting the wireless interface. First it tries to ping a given IP with `ping` command.
Then `$?` represents the exit code of the previous command. In our case, previous command is `ping`. If `ping` command fails will output a different exit code(not 0). Then the code part inside the `if` will be executed. It will turn off, wait 5 seconds and re-start the wireless interface `wlan0`.
And make sure you have necessary execute permissions for the script.
Open up the cron tab editor by `crontab -e` and add the following lines to the bottom of the file.
This script will run every 5 minutes with sudo permission. And the script's output is redirected to /dev/null hence won't clog your sys logs.
Writing checkwifi.sh
You can just copy paste this script into "/usr/local/bin/checkwifi.sh"
ping -c4 192.168.1.1 > /dev/null if [ $? != 0 ] then echo "No network connection, restarting wlan0...!" /sbin/ifdown 'wlan0' sleep 5 /sbin/ifup --force 'wlan0' fi
What we are trying to do is, we are restarting the wireless interface. First it tries to ping a given IP with `ping` command.
Then `$?` represents the exit code of the previous command. In our case, previous command is `ping`. If `ping` command fails will output a different exit code(not 0). Then the code part inside the `if` will be executed. It will turn off, wait 5 seconds and re-start the wireless interface `wlan0`.
And make sure you have necessary execute permissions for the script.
sudo chmod 775 /usr/local/bin/checkwifi.sh
Adding a Cron Job
Open up the cron tab editor by `crontab -e` and add the following lines to the bottom of the file.
*/5 * * * * /usr/bin/sudo -H /usr/local/bin/checkwifi.sh >> /dev/null 2>&1
This script will run every 5 minutes with sudo permission. And the script's output is redirected to /dev/null hence won't clog your sys logs.