29

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 heard that systemd has some python binds, but as far as I saw they only cover the journal.

9
  • So you're looking for a systemd module/package? Commented Nov 11, 2015 at 8:13
  • Am I? Well I want to talk with systemd as direct as possible. I don't want to exit the python enviroment and ask the system to do it for me, if there is a way to tap in more directly. Isn't there some kind of API, so I can talk to systemd? Commented Nov 11, 2015 at 8:16
  • 1
    Understand now, run systemd command more pythonic. :P Commented Nov 11, 2015 at 8:20
  • And I found this project, is it helpful? Commented Nov 11, 2015 at 8:25
  • 1
    Systemd also has a DBus API Commented Nov 11, 2015 at 8:35

1 Answer 1

35

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')
Sign up to request clarification or add additional context in comments.

1 Comment

I posted a similar follow-up question here: Starting a users systemd service via python and dbus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.