Search code examples
pythondbusfreedesktop.org

How can I fetch all systemd1 devices?


I wrote the code below to try and detect if a specific device is attached through USB. I'd like to iterate through the attached devices.

def scanCameraInterfaces(self):
    ud_manager_obj = dbus.SystemBus().get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    om = dbus.Interface(ud_manager_obj, 'org.freedesktop.systemd1.Unit')

    try:
        for k, v in om.GetManagedObjects().items():
            print(k)
            print(v)
    except Exception:
        print("No devices found...")

However, this will always print "No devices found...". So I removed the try, so I could see the error. It throws this: dbus.exceptions.DbusException: org.freedesktop.DBus.Error.AccessDenied: Rejected send message, 2 matched rules: type="method_call", sender=":1.39" (uid=1000 pid=1009 comm="python3 usbtest.py") interface="org.freedesktop.systemd1.Unit" member="GetManagedObjects" error name="(unset)" request_reply="0" destionation=":1.1" (uid=0 pid=1 comm="/sbin/init splash ").

What am I doing wrong?


Solution

  • I find the pydbus D-Bus bindings easier to work with.

    For example to get a list of all the units with the *usb* pattern in them:

    import pydbus
    systemd = pydbus.SystemBus().get('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    for units in systemd.ListUnitsByPatterns([], ['*usb*']):
        print(units[0])
    

    To get a list of all the systemd1 methods using Python:

    • dir(systemd)

    On the command line:

    • busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1