Stuff I Learned Today (But Didn't Really Want To)

I had this idea for doing a MarcoPolo-like script that required me to grab a list of all the Wi-Fi SSIDs that my Eee PC saw nearby, and instead of using iwlist like everyone else, I decided to use the Python dbus bindings and query NetworkManager for the info it already had.

Ought to be simple, right?

Well, no. As is usual, it is damn near impossible to find structured documentation regarding bleeding-edge Linux packages, and the API changed from 0.6.x to 0.7.x (and, of course, I’m running 0.7.whatever right now), so I had to Google for stuff until I came across cnetworkmanager, whose very internal structure is a testament to the insane amount of changes NetworkManager has gone through.

After poking around inside it a bit, I came up with this simple script that grabs the list of SSIDs NetworkManager 0.7.x knows about:

import dbus

NM = 'org.freedesktop.NetworkManager'
NMP = '/org/freedesktop/NetworkManager'
NMI = NM + '.Device'
PI = 'org.freedesktop.DBus.Properties'

def list_ssids():
  # get the base NetworkManager object and bind an interface  to it
  bus = dbus.SystemBus()
  nm = bus.get_object(NM,NMP)
  nmi = dbus.Interface(nm,NM)
  # Iterate over the devices queried via the interface
  for dev in nmi.GetDevices():
    # get each and bind a property interface to it
    devo = bus.get_object(NM,dev)
    devpi = dbus.Interface(devo,PI)
    # Single out the Wi-Fi ones
    if devpi.Get(NM,'DeviceType') == 2:
      wdevi = dbus.Interface(devo,NMI + '.Wireless')
      for ap in wdevi.GetAccessPoints():
         apo = bus.get_object(NM,ap)
         api = dbus.Interface(apo,PI)
         # unpack the SSID string
         print ''.join(["%c" % b for b in api.Get(NMI,'Ssid')])

if __name__ == '__main__':

This is of dubious (and most likely ephemeral) interest, but it might be useful to someone.

I will eventually figure out how to get NetworkManager to connect to a specific SSID, but there is one bit of missing functionality that strikes me as obvious (and that was why I stuck to trying to figure out dbus until I had enough) – building a dbus listener that gets notified every time a new Wi-Fi network pops up, which is left as an exercise to the reader.

See Also: