You are not logged in.
I have a laptop, which means I often want to connect to the nearest available free and unencrypted wireless hotspot. To avoid from having to set up a netcfg profile each time -- or randomly connecting via rc.d/network --, I decided to write my first shell script which allow me to connect to any wireless network via only its ESSID, which is assumed to be known beforehand.
This script also assumes that you have and use dhcpcd and iwconfig and that your wireless device interface is eth0. If it is not eth0, you should change the line in the script where it's the INTERFACE variable is defined.
To use the script, copy it into a file called "hotspot", chmod 755 it, and put it in /usr/bin or /usr/local/bin, and write at the command line: $ sudo hotspot <essid>, where <essid> is the name of the network (excluding the angle brackets). Below is an example scenario:
$ sudo hotspot LINKSYS
Disconnect from NETGEAR? [y/n] y
If you are already connected to a network, you will be prompted with request to confirm your decision to change or update your connection.
#!/bin/bash
# Use this script to connect to a wireless network via dhcpcd given an ESSID.
# If already connected, select whether to re-connect or switch the connection.
# If not already connected, then connect. The user must have sudo access.
if [ $(id -u) != 0 ]
# user is has root id;
then
echo "Must be run as root, exiting..."
exit 1
fi
INTERFACE='eth0'
DHCPCD='dhcpcd'
OLDESSID=`iwconfig $INTERFACE | grep -e $INTERFACE | awk -F\" '{print $2}'`
if [ $1 ]
then
ESSID=$1
else
echo -ne "Enter ESSID: ";
read ESSID
fi
if ps aux | grep $DHCPCD > /dev/null
# dhcpcd is already running;
then
if [ $OLDESSID -a $OLDESSID = $ESSID ]
then echo -ne "Reconnect to $OLDESSID? [y/n] "
else echo -ne "Disconnect from $OLDESSID? [y/n] "
fi
read RESPONSE
RESPONSE=`echo $RESPONSE | tr '[:lower:]' '[:upper:]'`
case $RESPONSE in
'N') echo "Goodbye!"; exit 0;;
'Y') dhcpcd -k;;
*) exit 1;;
esac
fi
iwconfig $INTERFACE essid $ESSID
if dhcpcd $INTERFACE $ESSID > /dev/null
then
echo "Connected to $ESSID!"
else
echo "$?: Couldn't connect to $ESSID!"
echo -e "\n$!\n"
fi
Room for improvement: This whole thing is, on some level, a kludge. At first glance, there should be a more reliable way of determining which network dhcpcd is leasing from. The script should also automatically determine your wireless device interface name. Besides these, I'm sure some of you can point out some others shortcomings as well.
Last edited by publius (2009-08-25 05:03:37)
Offline