Saturday, 5 April 2014

Rebooting OpenWRT automatically when network is down

Here is another useful script I found online. The point here is to regularly check the state of the network connection by pinging an IP address if the connection you want to check is the Internet, I recommend using Google's DNS (8.8.8.8).

I'm using theis script on a TP-Link TL-WR703n router that I leave behind with an OpenVPN server and a OVH dynamic DNS handled by this script. Since I can physically reboot the router very infrequently, I want to put all chances on my side, should something go wrong.

Note 1: apparently the WR703n has a wifi bug that makes it crash every now and then (every 10 days?). This script should solve the issue.

Note 2: The script below has been modified to restart all network instead of just the wifi in case of problem.

Here are my setup notes:

Step 1: Copy the script in (e.g.) /root

#! /bin/sh
# Checks if the wifi conn is up.  If not, it tries to restart
# the wifi.  If that fails, then reboot.
if ping -c 1 192.168.77.1 > /dev/null
then
  echo nothing > /dev/null
else
  /etc/init.d/network restart
  sleep 30
  if ping -c 192.168.77.1 > /dev/null
  then
    echo nothing > /dev/null
  else
    date >> /root/reboot.log
    reboot
  fi
fi
The original (unmodified) script can be found here.

Step 2: Update the permission for execution

chmod +x /root/updateDynhost

Step 3: Open crontab to add the line calling our script

crontab -e

Step 4: add the line to run the command every 10mins

Press 'i' to insert the line:
0,10,20,30,40,50 * * * * /root/updateDynhost

Step 5: Quit vi (used to edit the crontab)

Press [ESC], type ':wq' (without the quotes), press [ENTER]

Step 6: Enable and start cron

/etc/init.d/cron enable
/etc/init.d/cron start