Register
It is currently Sun Dec 21, 2014 7:02 am

A wlan script to associate with AP's


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Wed Sep 20, 2006 2:39 pm   

Joined: Tue Sep 19, 2006 8:55 am
Posts: 3
Not sure where to post this, but programming seems at least a tad bit close.


I've wrote a script which lists all nearby wireless access points. With it, you can select one of those networks and automatically associate with it, or you can choose to automatically connect to the strongest access point (unencrypted or encrypted).

Dependencies are
1. wireless_tools (iwconfig,iwlist)
2. wpa_supplicant (for connecting to WPA networks)
3. dhcpcd (may with some minor editing work with others)

This script is written for archlinux, and I need help with two things
1. Test/debug the script for archlinux users
2. Test/debug the script for other distro users.

It's my general opinion that it will work for most arch-systems, and likely with others. But it's hard to be sure without having anyone really testing it with others. So for my personal system this script works flawless.
The script doesn't write any config files, so no backups are neccessary.

Code:
The script, lsnet, can be found here:
www20.brinkster.com/warranty/lsnet.txt




Cheers


Top
 Profile ICQ  
 PostPosted: Thu Sep 21, 2006 9:19 am   
Site Admin
User avatar

Joined: Sun May 15, 2005 9:36 pm
Posts: 673
Location: Des Moines, Iowa
Moved to the sandbox......

btw... you can post the code here too if you like.....


Top
 Profile WWW  
 PostPosted: Thu Sep 21, 2006 11:47 am   

Joined: Tue Sep 19, 2006 8:55 am
Posts: 3
Ok, the script comes here:

Code:

#!/bin/bash

# :: READ THE DESCRIPTION A FEW ROWS DOWN ::

# Copyright (c)2006 Johan Sjöberg
# kernelcfg@gmail.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# http://www.gnu.org/licenses/gpl.txt
#
# A copy of the GNU GPL may be obtained on the web at:
#
#   http://www.gnu.org/licenses/gpl.txt
#
# or by writing to:
#
#   Free Software Foundation, Inc.
#   59 Temple Place - Suite 330
#   Boston, MA 02111-1307, USA
#


#
# ===// DESCRIPTION //=========================================================
#
# Utility for displaying and selecting wireless networks.
# Written for archlinux but may be used by others. Users of other dhcp clients than
# dhcpcd might need to revisit and edit the dhcp function of this script.
# This script does not write or read any config files, so no backups necessary.
#
# Depends on 'wireless_tools','wpa_supplicant' and whatever network driver you are using.
#
# It assumes that your wireless networking is fully functional prior to executing this script.
# Any encrypted network must be configuered manually in i.e. wpa_supplicant.conf.
#
# If a network is encrypted, wpa_supplicant will automatically be run with $IWOPTS as
# argument. No other encryption program is nor will be supported.
#


# Your wlan interface
WLAN="eth1"

# Operating mode of the wireless device
MODE="managed"

# Path to your wpa_supplicant configuration file
WPA_CFG="/etc/wpa_supplicant.conf"

# Options to pass to wpa_supplicant
IWOPTS="-D wext"

# Name of the DHCP client. Leave blank to skip dhcp.
# Don't include a search path for the DHCP option
DHCP="dhcpcd"

# Set to no if you don't want to warn if wpa_supplicant is missing
WPA_WARN="yes"

# ===// End configurables //===================================================

# Color variables
BLUE="\e[1m\e[34m"
GREEN="\e[0;32m"
GREY="\e[0m\e[37m"
BRED="\e[1m\e[31m"
RED="\e[0;31m"
DEFAULT="\e[0m"
BS="\033[1m" #bold start
BE="\033[0m" #bold end


# Some checks to see if dependencies are a match
if [ "$(which ifconfig 2>/dev/null)" == "" ]; then
   echo "Depends on net-tools ( in archlinux: pacman -Sy net-tools )"
   exit;
fi

if [ "$(which iwconfig 2>/dev/null)" == "" ]; then
   echo "Depends on wireless_tools ( in archlinux: pacman -Sy wireless_tools )"
   exit
fi

if [ "$WPA_WARN" == "yes" ] && [ "$(which wpa_supplicant 2>/dev/null)" == "" ]; then
   echo -e "  \nYou need an encryption program to connect to encrypted networks. "
   echo -e "  The most common is wpa_supplicant which allows WPA encryption as explained below:\n"
   echo -e "  ${BS}WPA :: Wi-fi Protected Access :: ${BE}"
   echo -e "  \tA secure protocol enforcing up to 256 bits of encryption."
   echo -e "  ${BS}WEP :: Wired Equivalent Privacy ::${BE}"
   echo -e "  \tA less secure protocol with several security exploits\n"
   echo -e "  You may still connect to unencrypted networks. Set WPA_WARN=\"no\""
   echo -e "  in this file to disable this warning message\n\n"
fi

if [ "$DHCP" != "" ] && [ "$(which $DHCP 2>/dev/null)" == "" ]; then
   echo "  DHCP client: $DHCP not found"
   echo "  Please configure the DHCP option in this file to match your DHCP client. "
   echo "  If you prefer to set your IP settings manually, please set DHCP=\"\" and"
   echo "  make sure your /etc/rc.conf looks somehting like this: (for archlinux users)"
   echo
   echo "      lo=\"lo 127.0.0.1\""
   echo "      eth1=\"eth0 321.321.321.3 netmask 255.255.255.0 broadcast 321.321.321..255\""
   echo "      INTERFACES=(lo eth1)"
   echo "      gateway=\"default gw 123.123.123.1\""
   echo "      ROUTES=(gateway)"
   echo
   echo "  In this example eth1 is your wireless interface. "; echo
   exit
fi

function getData(){
   list=`/usr/sbin/iwlist ${WLAN} scan | grep -e '\(Quality\|ESSID\|Chan\|Encryption\)'`

   # Insert all essential network values into categorized arrays
   IFS=$'\n'
   ESSID=(`awk -F ':' '/ESSID/ {print $2}' <<< "$list"`)
   IFS=$' \t\n' #Back to default
   CHAN=(`awk -F ':' '/ Channel:/ {print $2}' <<< "$list"`)
   ENCRYPTION=(`awk -F ':' '/Encryption/ {print $2}' <<< "$list"`)
   QUALITY=(`awk -F '=' '/Quality/ {print $2}' <<< "$list" | awk '{print $1}'`)


   # Display all available networks
   if [ "$1" != "suspend_output" ]; then
      echo -e "\n\n $BS Available networks: $BE"
      echo -e " ${BRED} --------------------------------------------- ${DEFAULT}"
      echo -e "${GREY}   note: \"-\" means unencrypted, \"x\" mean encrypted ${DEFAULT}\n"
   fi

   # Check if any networks were returned at all
   if [ "${CHAN[0]}" == "" ]; then
      echo -e "  \n${BS}No nearby accesspoints, try again later.${BE}\n"
      exit
   fi

   i=0
   for c in ${CHAN[@]}; do

      # A variant to display encryption
      if [ "${ENCRYPTION[$i]}" == "on" ]; then
         CRYPT[i]="x"
      else
         CRYPT[i]="-"
      fi   

      # List all networks
      if [ "$1" != "suspend_output" ]; then
         echo -e "${DEFAULT}    $BS ${i}. $BE Quality:\
         ${QUALITY[i]}  ${CRYPT[$i]}  Essid:${BLUE} ${ESSID[i]}"
      fi
      i=$[$i+1]
   done

   if [ "$1" != "suspend_output" ]; then
      echo -e "\n${DEFAULT}"
      echo " Run this script with root access for changes to take effect."
      echo -e "${RED} Select network: [0-9] or [q] to exit, [d] to disassociate ${DEFAULT}"
   fi
}

function dhcp(){
   # Check if dhcp is running
   pid=`pidof $DHCP`
   if [ "$pid" != "" ]; then
      kill $pid
      sleep 1
   fi

   # If dhcpcd is used, and pid is left over
   if [ -f /etc/dhcpcd/dhcpcd-$WLAN.pid ]; then
      rm -f /etc/dhcpc/dhcpcd-${WLAN}.{pid,cache} >/dev/null 2>&1
   fi

   printf "  $ Retrieving settings from dhcp ... "
   `/usr/sbin/$DHCP $WLAN`
   sleep 1
   IP="`ifconfig eth1 | grep "inet addr" | awk '{print $2}' | sed -e 's/addr://'`"
   if [ "$IP" != "" ]; then
      printf "${GREEN}done${DEFAULT}\n    IP-address: $IP\n"
   else
      printf "${RED}FAIL${DEFAULT}\n"
   fi
}


function wpa(){
   printf "  $ Network is encrypted, running wpa_supplicant ... "
   
   # If wpa_supplicant is already running, kill it
   pid=`pidof wpa_supplicant`
   if [ "$pid" != "" ]; then
      kill $pid
   fi

   /usr/sbin/wpa_supplicant -wB -i $WLAN -c ${WPA_CFG} ${IWOPTS} 2>/dev/null
   [ "$?" == "0" ] && printf "${GREEN}done${DEFAULT}\n"
   [ "$?" != "0" ] && printf "${RED}FAIL${DEFAULT}\n"
}


function usage(){
   echo "  Usage: lsnet [-h,-wpa,-a [u]]"
   echo "  Example usage: "
   echo "    lsnet -a    | associates with the strongest AP"
   echo "    lsnet -au   | associates with the strongest unencrypted AP"
   echo "    lsnet -wpa  | generate data for wpa_supplicant.conf"
}


# Associate with the AP
# Parameter: Index for array ESSID for the ESSID to set
function associate(){
   # Apply network settings
   printf "  $ Associating with ${BLUE}${ESSID[$1]}${DEFAULT} ... "
   essid=`sed -e 's/\"//g' <<< ${ESSID[$1]}`
   if [ "`id -u`" != "0" ]; then
      printf "FAIL\n"
      echo -e "  You must be ${RED}root${DEFAULT} for changes to take effect."
      exit
   fi

   /usr/sbin/iwconfig $WLAN essid "$essid" mode "$MODE" channel ${CHAN[$1]} 2>/dev/null
   tmp=$?
   sleep 1
   [ "$tmp" == "0" ] && printf "${GREEN}done${DEFAULT}\n"
   [ "$tmp" != "0" ] && printf "${RED}FAIL${DEFAULT}\n"

   printf "  $ Bringing interface $WLAN up ... "
   /sbin/ifconfig $WLAN up 2>/dev/null
   tmp=$?
   sleep 1
   [ "$tmp" == "0" ] && printf "${GREEN}done${DEFAULT}\n"
   [ "$tmp" != "0" ] && printf "${RED}FAIL${DEFAULT}\n"

      
   # If encrypted, run wpa_config
   if [ "${CRYPT[$1]}" == "x"  ]; then
      wpa
   fi


   # Get ip address from dhcp
   if [ "${DHCP}" != "" ]; then
      dhcp
   fi

   echo "  Network is now configuered"
   exit
}


# Connect to the strongest access point
# If script arguments are -au, associate with the strongest unencrypted AP.
# Otherwise associate with the strongest AP, encrypted or not.
function autoCon(){
   getData "suspend_output"
   strongest=-1
   strongest_i=-1

   # If param u is set, find the strongest unencrypted AP
   if [ "$1" == "-au" ]; then
      for ((i=0; i<=$(( ${#CRYPT[@]} - 1 )) ; i++)); do
         if [ "${CRYPT[$i]}" == "-" ]; then
            curr=`sed -e 's/\/.*//' <<< ${QUALITY[$i]}`
            if [ "$curr" -gt "$strongest"  ] ; then
               strongest=$curr
               strongest_i=$i
            fi
         fi
      done
      echo -e "\n  ${BS}Mode:${BE} Associate with the strongest un-encrypted Access Point (AP)"

      #Check if any unencrypted networks was found at all
      if [ "$strongest_i" = "-1" ]; then
         echo -e "  No unencrypted networks found. Please try again later.\n"
         exit
      fi

   # Else find the strongest AP, encrypted or not
   # getData already made sure there will be at least one network
   else
      for ((i=0; i<=$(( ${#QUALITY[@]} - 1 )) ; i++)); do
         curr=`sed -e 's/\/.*//' <<< ${QUALITY[$i]}`

         if [ "$curr" -gt "$strongest" ]; then
            strongest=$curr
            strongest_i=$i
         fi
      done
       echo -e "\n  Mode: Associate with the strongest Access Point (AP)"
   fi

   echo -e "  Selected Access Point:${BLUE} ${ESSID[$strongest_i]}  ${DEFAULT}\n"
   associate $strongest_i
}



function configWPA(){
   echo "  This will help you generate a configuration file for wpa_supplicant. "
   if [ "which wpa_supplicant 2>/dev/null" == "" ]; then
      echo "  wpa_supplicant not found on your system, exiting ..."
      exit
   fi
   echo
   echo "  Imagine the case where you will make a WPA connection to your own Access Point(AP) / router."
   echo -e "  Please supply the WPA passphrase that the AP uses (8..63 characters)\n"
   printf "  pass:\$ "
   read passphrase
   echo -e "  Type in the SSID that the AP is using\n"
   printf "  essid:\$ "
   read ssid
   entry=`wpa_passphrase $ssid $passphrase`
   echo -e "  Add this to your /etc/wpa_supplicant.conf file\n"
   echo "$entry"
   exit
}


# Code reminder to self: [[ "$1" != -[ha] ]]
# Check script parameters
case $1 in
   -h | --help )
      usage
      exit
      ;;
   -a | -au | --auto )
      autoCon $1
      exit
      ;;
   -wpa )
      configWPA
      ;;
      
   "" )
      getData
      ;;
   * )
      usage
      exit
      ;;
esac


# Select network and associate with that AP
while [ /bin/true ]; do
  read cmd
  case $cmd in
   [[:digit:]] )
      if [ "${CHAN[$cmd]}" != "" ]; then   
         associate $cmd
      fi
      echo "Number doesn't match any available network"
      break
      ;;
     d )
        echo "Disassociating with any accesspoints"
      iwconfig "$WLAN" essid "none"
      echo "Done"
      exit
      ;;
     q )
        echo "Exiting ..."
      exit 0
      ;;
     * )
        echo "Please input a number";;
  esac
done




Top
 Profile ICQ  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP