UDisks2 Python Automounting

Yet another full evening spent reading forums and mailing lists trying to hack together a few lines of code. Thanks, DBus.

The following Python snippet auto mounts USB drives (I needed on an appliance with no any running evoluted desktop environment doing it).

import dbus
from dbus.mainloop.glib import DBusGMainLoop
bus = dbus.SystemBus()
def callback_function(path, interfaces):
    obj = bus.get_object('org.freedesktop.UDisks2', path)
    iface = dbus.Interface(obj, 'org.freedesktop.UDisks2.Filesystem')
    path = iface.get_dbus_method('Mount', dbus_interface='org.freedesktop.UDisks2.Filesystem')([])
    print "Mounted at %s" % (path)
  except ValueError:
iface  = 'org.freedesktop.DBus.ObjectManager'
signal = 'InterfacesAdded'
bus.add_signal_receiver(callback_function, signal, iface)

import gobject
loop = gobject.MainLoop()

Credits: this, this and this.

Be aware that you will also need to tune your Polkit configuration to unlock permissions.