25

Is there a way to start/restart a systemd service via python?

I know that I can make a system call - but then I also could write this in shell script...

from subprocess import call
call(["systemctl", "restart service"])

I heared systemd has some python binds, but as far as I saw it they only cover the journal

Maximilian Kindshofer
  • 2,753
  • 3
  • 22
  • 37

1 Answers1

30

You can use systemd's DBus API to call the RestartUnit method of the Manager (need of sufficient privileges, else it won't work)

import dbus
sysbus = dbus.SystemBus()
systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager')
job = manager.RestartUnit('sshd.service', 'fail')
doekman
  • 18,750
  • 20
  • 65
  • 86
Cilyan
  • 7,883
  • 1
  • 29
  • 37
  • I posted a similar follow-up question here: [Starting a users systemd service via python and dbus](https://stackoverflow.com/q/42088406/2851664). – sebix Feb 08 '17 at 07:33