Package: pystemd
pystemdThis library allows you to talk to systemd over dbus from python, without
actually thinking that you are talking to systemd over dbus. This allows you to
programmatically start/stop/restart/kill and verify services status from
systemd point of view, avoiding executingsubprocess.Popen(['systemctl', ...and then parsing the output to know the result.Show don't tellIn software as in screenwriting, it's better to show how things work instead of
tell. So this is how you would use the library from a interactive shell.In [1]: from pystemd.systemd1 import Unit
In [2]: unit = Unit(b'postfix.service')
In [3]: unit.load()Note: you need to callunit.load()because by defaultUnitwill not load the
unit information as that would require do some IO (and we dont like doing io on a class constructor).
You can autoload the unit byUnit(b'postfix.service', _autoload=True)or using the unit as a
contextmanager likewith Unit(b'postfix.service'): ...Once the unit is loaded, you can interact with it, you can do by accessing its
systemd's interfaces:In [4]: unit.Unit.ActiveState
Out[4]: b'active'

In [5]: unit.Unit.StopWhenUnneeded
Out[5]: False

In [6]: unit.Unit.Stop(b'replace') # require privilege account
Out[6]: b'/org/freedesktop/systemd1/job/6601531'

In [7]: unit.Unit.ActiveState
Out[7]: b'inactive'

In [8]: unit.Unit.SubState
Out[8]: b'running'

In [9]: unit.Unit.Start(b'replace') # require privilege account
Out[9]: b'/org/freedesktop/systemd1/job/6601532'

In [10]: unit.Unit.ActiveState
Out[10]: b'active'

In [11]: unit.Service.GetProcesses() # require systemd v238 and above
Out[11]:
[(b'/system.slice/postfix.service',
    1754222,
    b'/usr/libexec/postfix/master -w'),
 (b'/system.slice/postfix.service', 1754224, b'pickup -l -t fifo -u'),
 (b'/system.slice/postfix.service', 1754225, b'qmgr -l -t fifo -u')]

In [12]: unit.Service.MainPID
Out[12]: 1754222Thesystemd1.Unitclass provides shortcuts for the interfaces in the systemd
namespace, as you se above, we have  Service (org.freedesktop.systemd1.Service)
and Unit (org.freedesktop.systemd1.Unit). Others can be found inunit._interfacesas:In [12]: unit._interfaces
Out[12]:
{'org.freedesktop.DBus.Introspectable': <org.freedesktop.DBus.Introspectable of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.DBus.Peer': <org.freedesktop.DBus.Peer of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.DBus.Properties': <org.freedesktop.DBus.Properties of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.systemd1.Service': <org.freedesktop.systemd1.Service of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.systemd1.Unit': <org.freedesktop.systemd1.Unit of /org/freedesktop/systemd1/unit/postfix_2eservice>}

 In [13]: unit.Service
 Out[13]: <org.freedesktop.systemd1.Service of /org/freedesktop/systemd1/unit/postfix_2eservice>Each interface has methods and properties, that can access directly asunit.Service.MainPID, the list of properties and methods is in.propertiesand.methodsof each interface.The above code operates on root user units by default. To operate on userspace units, explicitly pass in a user mode DBus instance:from pystemd.dbuslib import DBus
with DBus(user_mode=True) as bus:
    unit = Unit(b"postfix.service", bus=bus)
    unit.load()Alongside thesystemd1.Unit, we also have asystemd1.Manager, that allows
you to interact with systemd manager.In [14]: from pystemd.systemd1 import Manager

In [15]: manager = Manager()

In [16]: manager.load()

In [17]: manager.Manager.ListUnitFiles()
Out[17]:
...
(b'/usr/lib/systemd/system/rhel-domainname.service', b'disabled'),
 (b'/usr/lib/systemd/system/fstrim.timer', b'disabled'),
 (b'/usr/lib/systemd/system/getty.target', b'static'),
 (b'/usr/lib/systemd/system/systemd-user-sessions.service', b'static'),
...

In [18]: manager.Manager.Architecture
Out[18]: b'x86-64'

In [19]: manager.Manager.Virtualization
Out[19]: b'kvm'Extras:We also includepystemd.run, the spiritual port of systemd-run
to python.example of usage:# run this as root>>>importpystemd.run,sys>>>pystemd.run([b'/usr/bin/psql',b'postgres'],machine=b'db1',user=b'postgres',wait=True,pty=True,stdin=sys.stdin,stdout=sys.stdout,env={b'PGTZ':b'UTC'})will open a postgres interactive prompt in a local nspawn-machine.You also get an interface tosd_notifyin the form ofpystemd.daemon.notifydocs.# run this as root>>>importpystemd.daemon>>>pystemd.daemon.notify(False,ready=1,status='Gimme! Gimme! Gimme!')And access to listen file descriptors for socket activation scripts.# run this as root>>>importpystemd.daemon>>>pystemd.daemon.LISTEN_FDS_START3>>>pystemd.daemon.listen_fds()1# you normally only open 1 socketAnd access if watchdog is enabled and ping it.importtimeimportpystemd.daemonwatchdog_usec=pystemd.daemon.watchdog_enabled()watchdog_sec=watchdog_usec/10**6ifnotwatchdog_usec:print(f'watchdog was not enabled!')foriinrange(20):pystemd.daemon.notify(False,watchdog=1,status=f'count{i+1}')time.sleep(watchdog_sec*0.5)print('sleeping for 30 seconds')time.sleep(watchdog_sec*2)print('you will never reach me in a watchdog env')We also provide basic journal interaction withpystemd.journaldocsimportloggingimportpystemd.journalpystemd.journal.sendv(f"PRIORITY={logging.INFO}",MESSAGE="everything is awesome",SYSLOG_IDENTIFIER="tegan")will result in the message (shorten for sake of example).{"SYSLOG_IDENTIFIER":"tegan","PRIORITY":"20","MESSAGE":"everything is awesome",...}InstallSo you like what you see, the simplest way to install pystemd is by:$pipinstallpystemdpystemd is packaged in a few distros like Fedora and Debian. As of Fedora 32 and in EPEL as of EPEL 8.It can be installed with:$sudodnfinstallpython3-pystemd# fedora$sudoaptinstallpython3-pystemd# debianwhich will also take care of installing any required dependencies. Keep in mind that most distros manage their own repos and version, and you may be getting old versions.Build  from sourceyou'll need to have:Python headers: Just use your distro's package (e.g. python-dev).systemd headers: Chances are you already have this. Normally, it is calledlibsystemd-devorsystemd-devel. You need to have at least v237.
Please note that CentOS 7 ships with version 219. To work around this, please readthis.systemd library: check ifpkg-config --cflags --libs libsystemdreturns-lsystemdif not you can installsystemd-libsorlibsystemddepending on your distribution, version needs to be at least
v237.gcc: or any compiler thatsetup.pywill accept.pkg-configcommand. Depending on your distro, the package is called "pkg-config", "pkgconfig" or a compatible substitute like "pkgconf"if you want to install from source then after you clone this repo all you need to do itspip install .In addition to previous requirements you'll need:setuptools: Just use your distro's package (e.g. python-setuptools).Cython: at least version 0.21a1, just pip install it or use the official
installation guide from cython homepage to get latesthttp://cython.readthedocs.io/en/latest/src/quickstart/install.html.Learning moreThis project has been covered in a number of conference talks:Using systemd in high level languagesatAll Systems Go! 2018systemd: why you should care as a Python developeratPyCon 2018Better security for Python with systemdatPyninsula #10AVagrant-based demowas also developed
for PyCon 2018.Licensepystemd is licensed under LGPL 2.1 or later.