Tuesday, February 12, 2008

Router Monitoring Script

If you have a Netgear DG* router and wish to automatically reconnect / reboot when your connection drops, try adding this script to your cron.hourly:

#!/bin/sh

# CheckRouterStatus
# Tristan Phillips
# Checks the status of a netgear DG* router and reconnects / reboots if not connected.
# Licensed under the terms of the GNU.

# Arguments:
# $1 = Ping target, use www.google.co.uk
# $2 = Router IP, normally 192.168.0.1 or 192.168.1.1
# $3 = The router username (admin)?
# $4 = Router password (password)?

# Check arguments are present
if [ "$1" = "" ] || [ "$2" = "" ] || [ "$3" = "" ] || [ "$4" = "" ]; then
echo usage: CheckRouterStatus.sh PingTarget RouterIP RouterUser RouterPassword
exit
fi

# Try the ping
echo Attempting to ping $1
ping -W 10 -c 8 $1 >/dev/null 2> /dev/null

# Check result
if [ $? -ne 0 ]; then

# The ping failed! Get Stats and disconnect the router
echo Ping failed, dumping stats and disconnecting router . . .
echo `date` Ping failed, here are the router stats: >> /var/log/RouterReboots
wget --user $3 --password $4 "http://$2/setup.cgi?next_file=stattbl.htm"
# Execute the first router command twice as authorization tends to fail...
wget --user $3 --password $4 "http://$2/setup.cgi?next_file=stattbl.htm"
grep ttext setup.cgi?next_file=stattbl.htm >> /var/log/RouterReboots
echo `date` Disconnecting router >> /var/log/RouterReboots
wget -q --user $3 --password $4 "http://$2/setup.cgi?todo=disconnect" > /dev/null 2> /dev/null

echo Waiting . . .
sleep 10

echo Connecting router . . .
echo `date` Connecting router >> /var/log/RouterReboots
# Async call to connect incase of timeout
wget -q --user $3 --password $4 "http://$2/setup.cgi?todo=connect" > /dev/null 2> /dev/null &
echo Waiting . . .
sleep 20

# Try again
echo Attempting to ping $1
ping -W 10 -c 8 $1 > /dev/null 2> /dev/null
# Check results
if [ $? -ne 0 ]; then
echo Ping failed . . .
echo `date` Disconnect / Connect cycle did not correct the issue! Trying a reboot . . . >> /var/log/RouterReboots
wget -q --user $3 --password $4 "http://$2/setup.cgi?todo=reboot" > /dev/null 2> /dev/null
else
echo Ping OK, Connection issue solved!
echo `date` connection issue solved. >> /var/log/RouterReboots
fi

# Be nice and logout
wget -q --user $3 --password $4 "http://$2/setup.cgi?todo=logout" > /dev/null 2> /dev/null

else
echo Ping OK
fi

#clean up
rm setup.cgi*

exit 0

1 comment:

Anonymous said...

Thanks Tristan - that is super useful. I have made some changes to suit my use case (pinging more hosts mainly) on http://forums.whirlpool.net.au/forum-replies.cfm?t=1161290&p=-1