Skip to content

Instantly share code, notes, and snippets.

@fijimunkii
Forked from afresh1/find_networks.sh
Created July 16, 2018 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fijimunkii/cb3cb8fd547ee0313dc1d210e9475d1b to your computer and use it in GitHub Desktop.
Save fijimunkii/cb3cb8fd547ee0313dc1d210e9475d1b to your computer and use it in GitHub Desktop.
A script to find and connect to known wifi networks on OpenBSD. Works for me on my iwn card in my laptop
#!/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="\([^ ]*\)"
conf_match=''
for m in "$dq" "$sq" "$sp"; do
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 's/^[[:space:]]*nwid \(.*\) chan .*$/\1/p' |
while read line ; do
if [ "${line% *}" != "$line" ]; then
line=${line%\"}
line=${line#\"}
fi
echo $line
done | 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
#!/bin/sh
if=$1
# I put this into my /etc/hostname.$if file:
# !/usr/local/bin/reconnect_network \$if &
# dhcp
if pgrep -f "$( basename $0 ).*$if" | grep -q -v ^$$\$; then
echo "Already running on $if"
exit 2
fi
ifconfig $if up
while true; do
if ifconfig $if | grep -q 'status: active'; then
sleep 5
elif ifconfig $if | head -1 | grep -q -v UP; then
echo exiting
exit
else
$(dirname $0)/find_network.sh $if
sleep 30
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment