Skip to content

Instantly share code, notes, and snippets.

@Lechindianer
Forked from afresh1/find_networks.sh
Created February 27, 2014 10:38
Show Gist options
  • Save Lechindianer/9247841 to your computer and use it in GitHub Desktop.
Save Lechindianer/9247841 to your computer and use it in GitHub Desktop.
#!/bin/sh
# find_network.sh - An OpenBSD Wireless Network configurator
# Looks for available networks listed at the end of the script
# Use this by adding "!/path/to/find_network.sh \$if" to your wlan hostname.if
if=$1
if [ -z "$if" ]; then
echo "Usage: $0 interface" >&2
exit 2;
fi
# Annoyingly have to build the list of possible matches
# because otherwise we can't quote things properly
# Probably a better solution for this . . .
dq='"\([^"]*\)"'
sq="'\([^']*\)'"
sp="\([^ ]*\)"
ifc_match=''
conf_match=''
for m in "$dq" "$sq" "$sp"; do
ifc_match="$ifc_match /^[[:space:]]*nwid $m chan.*/{s//\1/p;d;};"
conf_match="$conf_match /^$m.*/{s//\1/p;d;};"
done
TMP=`mktemp wifinwid-TMP-XXXXXX`
trap 'rm -f $TMP; exit 1' 0 1 2 15
# First reset the interface as that makes the scan more reliable
ifconfig $if -bssid -chan -nwid -nwkey -wpa -wpakey down
# Then actually perform the scan
ifconfig $if scan | sed -ne "$ifc_match" | sort -u > $TMP
if [ ! -s $TMP ]; then
echo "No networks found"
exit 3
fi
while read conf; do
[ -z "$conf" ] && continue # skip empty
[ X"${conf#\#}" == X"${conf}" ] || continue # skip comments
nwid=`echo "$conf" | sed -ne "$conf_match"`
if grep -q "^$nwid$" $TMP; then
# need to eval for possible quotes in $conf
echo "Connecting to $nwid"
eval ifconfig $if nwid $conf up
break
fi
done <<EOL
# List your nwid's plus any options here, including quotes if necessary
# This list is in order of preference, it looks for these networks in order.
# This could easily become an external file
"#SFO FREE WIFI" chan 44
myHouse nwkey "MyKey"
linksys
EOL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment