Skip to content

Instantly share code, notes, and snippets.

@farhaven
Created August 31, 2012 19:50
Show Gist options
  • Save farhaven/3558101 to your computer and use it in GitHub Desktop.
Save farhaven/3558101 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python3.2
import encodings
import os
import re
import subprocess
import syslog
import sys
import time
class Network(object):
def __init__(self, setup, prio):
self.prio = prio
self.setup = setup
device = "wpi0"
networks = { "Foo": Network([ "wpakey fnord" ], prio=1) }
class AccessPoint(object):
def __init__(self, essid, bssid, signal):
if essid[0] == "\"" and essid[-1] == "\"":
self.essid = essid[1:-1]
else:
self.essid = essid
self.bssid = bssid
self.signal = signal
def generate_config(nw):
if nw is None:
return
syslog.syslog("Configuring " + device + " for ESSID \"" + nw.essid + "\" (BSSID: " + nw.bssid + ")")
subprocess.Popen(["ifconfig", device, "up", "bssid", nw.bssid, "nwid", nw.essid]).wait()
for param in networks[nw.essid].setup:
cmd = ["ifconfig", device]
cmd.extend(param.split())
subprocess.Popen(cmd).wait()
def select_network(aps):
aps = list(sorted(filter(lambda x: x.essid in networks, aps), key=lambda x: (float(x.signal) * networks[x.essid].prio), reverse=True))
return aps[0] if len(aps) != 0 else None
def connect():
re_data = re.compile("\t\tnwid (.+) chan [0-9]+ bssid ([0-9a-f:]+) ([0-9]+)dB")
subprocess.Popen(["ifconfig", device, "down"]).wait()
p = subprocess.Popen(["ifconfig", device, "scan"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate(None)
p.wait()
aps = []
for line in stdout.splitlines():
m = re_data.match(encodings.utf_8.decode(line)[0])
if m is None:
continue
essid = m.groups()[0]
bssid = m.groups()[1]
signal = m.groups()[2]
aps.append(AccessPoint(essid, bssid, signal))
syslog.syslog("found " + str(len(aps)) + " access point(s):")
for n in aps:
syslog.syslog((" " * (2 - len(n.signal))) + n.signal + "dB: " + n.bssid + "\t" + n.essid + ("\tknown" if n.essid in networks else ""))
generate_config(select_network(aps))
syslog.closelog()
if __name__ == "__main__":
if len(sys.argv) == 2:
device = sys.argv[1]
connect()
time.sleep(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment