wifi.sh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/bin/bash
  2. # Finds the strongest unencrypted AP and tries to connect to it via dhcp
  3. # Call this script like "wifi.sh wlan0"
  4. TEMP=/tmp/bestap.tmp
  5. LOCK=/var/lock/bestap.lock
  6. if [ `whoami` != "root" ];then
  7. echo "Sorry, you need to be root to run this program"
  8. exit 1
  9. fi
  10. if [[ -z $1 ]];then
  11. echo "USAGE: $0 device"
  12. exit 1
  13. else
  14. interface=$1
  15. fi
  16. # Checking for lock
  17. if [[ -e $LOCK ]];then
  18. exit 1; # Too simply nothing to do here :)
  19. else
  20. touch $TEMP $LOCK
  21. fi
  22. # Proggy
  23. iwlist $interface scan > $TEMP
  24. NumAPs=`cat $TEMP | grep ESSID | wc -l`
  25. BestAP=0
  26. BestQuality=-1
  27. for i in `seq 1 $NumAPs`;
  28. do
  29. # Check if AP is encrypted
  30. Encryption=`cat $TEMP | grep Encryption | head -n$i | tail -n1 | cut -d":" -f2`
  31. if [ $Encryption = "off" ]; then
  32. # Find AP with the highest quality
  33. QUALITY=`cat $TEMP | grep Quality | head -n$i | tail -n1 | cut -d":" -f2 | cut -d"/" -f1 | sed 's/ //g'`
  34. QUALITY=`cat $TEMP | grep Quality | head -n$i | tail -n1 | cut -d"=" -f2 | cut -d"/" -f1 | sed 's/ //g'`
  35. if [ "$QUALITY" -gt "$BestQuality" ]; then
  36. BestQuality=$QUALITY
  37. BestAP=$i
  38. fi
  39. fi
  40. done
  41. if [ $BestAP -gt 0 ]; then
  42. # Yay, we found an unencrypted AP:
  43. echo Connecting to...
  44. ESSID=`cat $TEMP | grep ESSID | head -n$BestAP | tail -n1 | cut -d'"' -f2`
  45. echo ESSID=$ESSID
  46. MODE=`cat $TEMP | grep Mode | head -n$BestAP | tail -n1 | cut -d":" -f2`
  47. echo Mode=$MODE
  48. CHANNEL=`cat $TEMP | grep Channel | head -n$BestAP | tail -n1 | cut -d"(" -f2 | sed 's/Channel.//g' | sed 's/)//g' | sed 's/ //g'`
  49. echo Channel=$CHANNEL
  50. # Connect
  51. echo iwconfig $interface essid $ESSID mode $MODE channel $CHANNEL
  52. if [ -e /etc/dhcpc/dhcpcd-${interface}.pid ]; then
  53. rm /etc/dhcpc/dhcpcd-${interface}.pid
  54. fi
  55. dhcpcd $interface
  56. # Cleanup
  57. fi
  58. rm -f $TEMP $LOCK