Page 1 of 1

Auto Wifi Script

Posted: Wed Feb 06, 2013 6:13 am
by Trcx
Hello all,

Here is a script that I wrote for my pi to connect to wifi (wpa), restart wpa_supplicant if the pi is not connect to the internet, and to add static ip adresses to the wifi driver if desired. I'm posting this in hopes that someone else finds this useful. To get the script working tweak the variables at the top of the file, and add

Code: Select all

post-up /path/to/script
under the wlan section of /etc/network/interfaces, be sure to chmod 755 the script.

Anyways here is the script, I find it suites my needs perfectly, but I am open to suggestions as for ways to improve it.

Code: Select all

#!/bin/bash

addip=( '192.168.1.250/24' '192.168.43.250/24' ) #sample leave blank for none
int='wlan0'
wpaconf='/etc/wpa_supplicant/wpa_config.conf'
loop='60' #check connectivity ever 60 seconds (20.16kB/day at 60 seconds)

function add_ip () {
  for ip in "${addip[@]}"; do
    ip addr add $ip dev $int
  done
}

function remove_ip () {
  for ip in "${addip[@]}"; do
    ip addr del $ip dev $int
  done
}

function start_wpa () {
  wpa_supplicant -B -i $int -c $wpaconf
  dhclient $int
  sleep 3
  add_ip
}

function stop_wpa () {
  killall  wpa_supplicant
  remove_ip
}

status=down
# slightly inefficient I know, but it works well
function wpa_status () {
  status=down
  if [ "$(pgrep wpa_supplicant)" != "" ]; then
    wget http://www.msftncsi.com/ncsi.txt -O /dev/null
    if [ "$?" == "0" ]; then
      status=up
    else # try a quick dns fix
      echo "nameserver 8.8.8.8" > /etc/resolv.conf
      wget http://www.msftncsi.com/ncsi.txt -O /dev/null                                    │       --follow-ftp                follow FTP links from HTML documents.                  
      if [ "$?" == "0" ]; then                                                              │       --follow-tags=LIST          comma-separated list of followed HTML tags.            
        status=up
      fi
    fi
  fi
}

pidfile=/tmp/wifi_wpa_autoconfig
#to prevent multiple instances
# this works because tmpfs (/tmp) is cleared upoun reboots
if [ -f $pidfile ]; then
  echo "Already Running"
  exit 1
else
  touch $pidfile
fi

while [ true ]; do
  wpa_status
  if [ "$status" == "down" ];then
    stop_wpa
    start_wpa
  fi
  sleep $loop
done