Tuesday, January 30, 2007

Script to Automatically Restart Wireless

First of all, welcome to "Four Thirds Pi", a blog I just created to hold musings on Python, Linux, OSS, etc.

Well, now for the first post...

I now have a script working that automatically restarts my network adapter if pings start to time out. I needed this because I have a flaky router and I want my Server (in my closet) to automatically recognize when it can connect again w/o having to hook up a monitor and type ifup -a.

So the script is as follows:

#! /bin/bash
# This script will ping a known host and restart the interface
# if the ping fails
# 9/6/06 RCH
#
# usage: keepwirelessup.sh [sleep_time]
#

NAME=keepwirelessup
PING_HOST="www.yahoo.com"

if [ -n "$1" ]; then
SLEEP_TIME=$1
else
SLEEP_TIME=3
fi

while true; do
ping -c 1 $PING_HOST &> /dev/null
if [ $? -ne "0" ]; then
ifdown -a
ifup -a
echo `date` Restarting Wireless... >> /var/log/$NAME.log
fi
sleep $SLEEP_TIME
done


I copied this script to /etc/init.d/, changed the permissions and ownership to root and then
added these lines to my /etc/rc.local file:

# Run my custom Keep Wireless Script Up
KEEP_WIRELESS_UP=/etc/init.d/keepwirelessup.sh
test -f $KEEP_WIRELESS_UP && nice -n -10 $KEEP_WIRELESS_UP &


Now, theoretically, my server should automatically reconnect when the connection resumes to the router.