Skip to content

Instantly share code, notes, and snippets.

@giu1io
Last active February 24, 2024 10:00
Show Gist options
  • Select an option

  • Save giu1io/d8d4695325a8d5cc429f to your computer and use it in GitHub Desktop.

Select an option

Save giu1io/d8d4695325a8d5cc429f to your computer and use it in GitHub Desktop.
Shell script that loads the WPA_supplicant configuration and use it to connect to available networks, if none is available it an AP is created. Include Wi-Fi watchdog service that checks that the connection is always working.
#!/bin/bash
WPA_SUPPLICANT_CONF="/etc/wpa_supplicant/wpa_supplicant.conf"
# this funcion is called once the connection is established,
# in this case a boot sound will be played to notify the user that everything is ready.
function connected {
aplay /root/Windows3.1.wav 2>&1 >/dev/null &
}
# function that tries to establish a connection, get a network in $temp from the WPA file
# and then goes through all available networks ($essid) to find a match.
function testConnect {
while [ $x -lt ${#essid[@]} ]; do
if [ "${temp[ssid]}" = "${essid[$x]}" ]
then
echo "Trying to connect to ${temp[ssid]}"
ssid="${temp[ssid]}"
ssid="${ssid%\"}"
ssid="${ssid#\"}"
iwconfig wlan0 essid "$ssid"
dhclient wlan0
connected
exit
fi
(( x++ ))
done
}
a=0
b=0
x=0
declare -a essid
declare -a address
# load in $essid and $address all available networks
while read line
do
case $line in
*ESSID* )
line=${line#*ESSID:}
essid[$a]="$line"
a=$((a + 1))
;;
*Address*)
line=${line#*Address:}
address[$b]="$line"
b=$((b + 1))
;;
esac
done < <(iwlist wlan0 scanning)
#load in $temp a network at time from the WPA supplicant file
declare -A temp
i=0
flag=0
while read line
do
case "$line" in
"network={")
flag=1
;;
"}")
#echo "${temp[*]}"
testConnect temp[@]
((i++))
flag=0
;;
*)
if [ "$flag" -eq 1 ]; then
IFS='=' read -a array <<< "$line"
key="${array[0]}"
temp[$key]="${array[1]}"
fi
esac
done < $WPA_SUPPLICANT_CONF
# if a connection hasn't been established create an hotspot
if ifconfig wlan0 | grep -q "inet addr:" ; then
echo "Already Connected"
# start the watchdog service
service wifi_watchdog start
connected
else
#we don't know if the watchdog service is running so stop it 'cause I haven't test it yet
service wifi_watchdog stop
echo "Network connection down! Inizializing hotspot:"
# set a static IP
ifconfig wlan0 192.168.0.1 netmask 255.255.255.0
# inizialize hotspot
hostapd -B -dd /etc/hostapd/hostapd.conf
# start dhcp
service udhcpd start
connected
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment