Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python -OO
- 'network mapper script'
- import sys, os, syslog, subprocess, re
- from collections import OrderedDict, defaultdict
- DEFAULT_INTERFACE = 'wlan0'
- INTERFACES = '/etc/network/interfaces'
- def mapper(interface): # network script calls with interface name
- log('mapper: interface = %s' % interface)
- if __debug__ and sys.stdin.isatty():
- print >>sys.stderr, 'enter mappings e.g "linksys wlan0-linksys", end with ^D'
- interfaces = mapping(sys.stdin.read() or read_interfaces())
- log('interfaces: %s' % interfaces)
- try:
- available = getlist(interface)
- except Exception, error:
- log('failed getting available APs: %s' % error)
- raise error
- log('available: %s' % available)
- chosen = ''
- for signal_strength in sorted(available.keys(), reverse = True):
- for essid in available[signal_strength]:
- log('looking for essid "%s" in interfaces %s' % (essid, repr(interfaces)))
- for key in interfaces:
- if essid == interfaces[key]:
- chosen = key
- break
- if chosen: break
- if chosen: break
- log('chosen: %s' % chosen)
- return chosen
- def read_interfaces(filename = INTERFACES):
- map_re = re.compile('^map\s+(.*)$')
- interfaces = '\n'.join([map_re.match(m).group(1)
- for m in readlines(filename, str.strip) if map_re.match(m)])
- log('interfaces: %s' % interfaces)
- return interfaces
- def readlines(filename, preprocess = None):
- log('reading lines in %s' % filename)
- infile = open(filename)
- data = map(preprocess, infile.readlines())
- infile.close()
- return data
- def getlist(interface):
- '''\
- get results of iwlist and make list of APs
- here's what it looks like:
- wlan0 Scan completed :
- Cell 01 - Address: AC:E2:15:23:4F:14
- Channel:1
- Frequency:2.412 GHz (Channel 1)
- Quality=28/70 Signal level=-82 dBm
- Encryption key:on
- ESSID:"INFINITUM7rxv"
- [etc...]
- '''
- log('attempting to get available APs from %s' % interface)
- ifup = sudo_command(['ifconfig', interface, 'up'])
- log('ifup %s: %s' % (interface, repr(ifup)))
- iwlisting = sudo_command(['iwlist', interface, 'scanning'])
- apdict = defaultdict(list)
- cell = re.compile('^Cell (\d+) - Address: ([0-9A-F:]{17})$')
- quality = re.compile('^Quality=(\d+)/(\d+)\s+Signal level=(-?\d+) dBm$')
- ssid = re.compile('^ESSID:(.*)$')
- for line in iwlisting:
- if cell.match(line):
- strength, essid = 0.0, ''
- elif ssid.match(line):
- match = ssid.match(line)
- apdict[strength].append(stripquotes(match.group(1)))
- elif quality.match(line):
- match = quality.match(line)
- strength = float(match.group(1)) / float(match.group(2))
- else:
- log('no match: %s' % line)
- return apdict
- def sudo_command(command_list):
- command = sudo(command_list)
- log('executing command: %s' % repr(command))
- output = subprocess.Popen(command,
- stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
- output.wait()
- result = map(str.strip, output.stdout.readlines())
- output.stdout.close()
- return result
- def sudo(command_list):
- if not os.geteuid() == 0:
- command_list.insert(0, 'sudo')
- return command_list
- def stripquotes(string):
- if string.startswith('"') and string.endswith('"') or \
- string.startswith("'") and string.endswith("'"):
- return string[1:-1]
- else:
- return string
- def mapping(data):
- '''\
- OrderedDict no help here because initscripts don't return list in order
- have to use signal strength or some other metric to choose best AP'''
- log('mapping data %s' % repr(data))
- datadict = {}
- for line in filter(None, data.split('\n')):
- log('line: "%s"' % line)
- last_space = line.rindex(' ')
- key = line[last_space + 1:]
- value = line[:last_space]
- datadict[key] = value
- return datadict
- def log(message):
- if False and __debug__ and sys.stdin.isatty():
- print >>sys.stderr, message
- else:
- syslog.syslog(message)
- backup_log = open('/tmp/network.log', 'a')
- print >>backup_log, message
- backup_log.close()
- if __name__ == '__main__':
- print mapper((sys.argv[1:2] or [DEFAULT_INTERFACE])[0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement