Advertisement
Guest User

map.py, mapper script for Debian /etc/network/interfaces

a guest
Dec 17th, 2013
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.04 KB | None | 0 0
  1. #!/usr/bin/python -OO
  2. 'network mapper script'
  3. import sys, os, syslog, subprocess, re
  4. from collections import OrderedDict, defaultdict
  5. DEFAULT_INTERFACE = 'wlan0'
  6. INTERFACES = '/etc/network/interfaces'
  7. def mapper(interface):  # network script calls with interface name
  8.  log('mapper: interface = %s' % interface)
  9.  if __debug__ and sys.stdin.isatty():
  10.   print >>sys.stderr, 'enter mappings e.g "linksys wlan0-linksys", end with ^D'
  11.  interfaces = mapping(sys.stdin.read() or read_interfaces())
  12.  log('interfaces: %s' % interfaces)
  13.  try:
  14.   available = getlist(interface)
  15.  except Exception, error:
  16.   log('failed getting available APs: %s' % error)
  17.   raise error
  18.  log('available: %s' % available)
  19.  chosen = ''
  20.  for signal_strength in sorted(available.keys(), reverse = True):
  21.   for essid in available[signal_strength]:
  22.    log('looking for essid "%s" in interfaces %s' % (essid, repr(interfaces)))
  23.    for key in interfaces:
  24.     if essid == interfaces[key]:
  25.      chosen = key
  26.      break
  27.    if chosen: break
  28.   if chosen: break
  29.  log('chosen: %s' % chosen)
  30.  return chosen
  31. def read_interfaces(filename = INTERFACES):
  32.  map_re = re.compile('^map\s+(.*)$')
  33.  interfaces = '\n'.join([map_re.match(m).group(1)
  34.   for m in readlines(filename, str.strip) if map_re.match(m)])
  35.  log('interfaces: %s' % interfaces)
  36.  return interfaces
  37. def readlines(filename, preprocess = None):
  38.  log('reading lines in %s' % filename)
  39.  infile = open(filename)
  40.  data = map(preprocess, infile.readlines())
  41.  infile.close()
  42.  return data
  43. def getlist(interface):
  44.  '''\
  45. get results of iwlist and make list of APs
  46.  
  47. here's what it looks like:
  48.  
  49. wlan0     Scan completed :
  50.          Cell 01 - Address: AC:E2:15:23:4F:14
  51.                    Channel:1
  52.                    Frequency:2.412 GHz (Channel 1)
  53.                    Quality=28/70  Signal level=-82 dBm  
  54.                    Encryption key:on
  55.                    ESSID:"INFINITUM7rxv"
  56.                    [etc...]
  57. '''
  58.  log('attempting to get available APs from %s' % interface)
  59.  ifup = sudo_command(['ifconfig', interface, 'up'])
  60.  log('ifup %s: %s' % (interface, repr(ifup)))
  61.  iwlisting = sudo_command(['iwlist', interface, 'scanning'])
  62.  apdict = defaultdict(list)
  63.  cell = re.compile('^Cell (\d+) - Address: ([0-9A-F:]{17})$')
  64.  quality = re.compile('^Quality=(\d+)/(\d+)\s+Signal level=(-?\d+) dBm$')
  65.  ssid = re.compile('^ESSID:(.*)$')
  66.  for line in iwlisting:
  67.   if cell.match(line):
  68.    strength, essid = 0.0, ''
  69.   elif ssid.match(line):
  70.    match = ssid.match(line)
  71.    apdict[strength].append(stripquotes(match.group(1)))
  72.   elif quality.match(line):
  73.    match = quality.match(line)
  74.    strength = float(match.group(1)) / float(match.group(2))
  75.   else:
  76.    log('no match: %s' % line)
  77.  return apdict
  78. def sudo_command(command_list):
  79.  command = sudo(command_list)
  80.  log('executing command: %s' % repr(command))
  81.  output = subprocess.Popen(command,
  82.   stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  83.  output.wait()
  84.  result = map(str.strip, output.stdout.readlines())
  85.  output.stdout.close()
  86.  return result
  87. def sudo(command_list):
  88.  if not os.geteuid() == 0:
  89.   command_list.insert(0, 'sudo')
  90.  return command_list
  91. def stripquotes(string):
  92.  if string.startswith('"') and string.endswith('"') or \
  93.   string.startswith("'") and string.endswith("'"):
  94.   return string[1:-1]
  95.  else:
  96.   return string
  97. def mapping(data):
  98.  '''\
  99. OrderedDict no help here because initscripts don't return list in order
  100.  
  101. have to use signal strength or some other metric to choose best AP'''
  102.  log('mapping data %s' % repr(data))
  103.  datadict = {}
  104.  for line in filter(None, data.split('\n')):
  105.   log('line: "%s"' % line)
  106.   last_space = line.rindex(' ')
  107.   key = line[last_space + 1:]
  108.   value = line[:last_space]
  109.   datadict[key] = value
  110.  return datadict
  111. def log(message):
  112.  if False and __debug__ and sys.stdin.isatty():
  113.   print >>sys.stderr, message
  114.  else:
  115.   syslog.syslog(message)
  116.   backup_log = open('/tmp/network.log', 'a')
  117.   print >>backup_log, message
  118.   backup_log.close()
  119. if __name__ == '__main__':
  120.  print mapper((sys.argv[1:2] or [DEFAULT_INTERFACE])[0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement