-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystemctl.py
54 lines (43 loc) · 1.69 KB
/
systemctl.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
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
"""
start / stop / status system service
"""
import subprocess
import sys
class SystemdService(object):
'''A systemd service object with methods to check it's activity, and to stop() and start() it.'''
def __init__(self, service):
self.service = service
def is_active(self):
"""Return True if systemd service is running"""
try:
cmd = '/bin/systemctl status {}.service'.format(self.service)
completed = subprocess.run( cmd, shell=True, check=True, stdout=subprocess.PIPE )
except subprocess.CalledProcessError as err:
print( 'ERROR:', err )
else:
for line in completed.stdout.decode('utf-8').splitlines():
if 'Active:' in line:
if '(running)' in line:
print('True')
return True
return False
def stop(self):
''' Stop systemd service.'''
try:
cmd = '/bin/systemctl stop {}.service'.format(self.service)
completed = subprocess.run( cmd, shell=True, check=True, stdout=subprocess.PIPE )
except subprocess.CalledProcessError as err:
print( 'ERROR:', err )
def start(self):
''' Start systemd service.'''
try:
cmd = '/bin/systemctl start {}.service'.format(self.service)
completed = subprocess.run( cmd, shell=True, check=True, stdout=subprocess.PIPE )
except subprocess.CalledProcessError as err:
print( 'ERROR:', err )
if __name__ == '__main__':
# monitor = SystemdService(sys.argv[1])
monitor = SystemdService(sys.argv[1])
monitor.is_active()