-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_systemd_service_access.py
64 lines (51 loc) · 2.37 KB
/
simple_systemd_service_access.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import dbus
class SimpleSystemDServiceAccess(object):
def __init__(self,name, mode = 'fail') -> None:
'''
provide service name (bla.service)
for possible modes refer to (StartUnit description) : https://www.freedesktop.org/wiki/Software/systemd/dbus/
'''
self.name = name
self.mode = mode
self.sysbus = dbus.SystemBus()
self.systemd1 = dbus.SystemBus().get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
self.manager = dbus.Interface(self.systemd1, 'org.freedesktop.systemd1.Manager')
def StartService(self):
'''
Will Start an Systemd Service if available
(Admin Rights needed !)
if service is not available or name is wrong dbus will rise an Exception !
'''
self.manager.StartUnit(self.name,self.mode)
def StopService(self):
'''
Will Stop an Systemd Service if available
(Admin Rights needed !)
if service is not available or name is wrong dbus will rise an Exception !
'''
self.manager.StopUnit(self.name,self.mode)
def RestartService(self):
'''
Will Restart an Systemd Service if available
(Admin Rights needed !)
if service is not available or name is wrong dbus will rise an Exception !
'''
self.manager.RestartUnit(self.name,self.mode)
def IsRunning(self) -> bool:
'''
Will check if an service is running.
Code is an copy from stackoverflow (https://stackoverflow.com/questions/43499880/how-to-extract-service-state-via-systemd-dbus-api)
will return True if service is running, and false is Service is not running
'''
status = False
try:
service = self.sysbus.get_object('org.freedesktop.systemd1',object_path=self.manager.GetUnit(self.name))
interface = dbus.Interface(service,dbus_interface='org.freedesktop.DBus.Properties')
ActiveState = interface.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
LoadState = interface.Get('org.freedesktop.systemd1.Unit', 'LoadState')
if LoadState == 'loaded' and ActiveState == 'active':
status = True
except dbus.exceptions.DBusException:
# dbus will rise Exception if not running ...
pass
return status