[英]How to stop and start a systemd service via python script w/o requiring sudo password
The following script allows me to check whether a systemd service
is active, and to stop or start the service.以下脚本允许我检查
systemd service
是否处于活动状态,以及停止或启动该服务。 When executing .stop()
or .start()
, how can I proceed to stopping and starting the service directly w/o having to supply the sudo password?当执行
.stop()
或.start()
如何继续进行到停止和直接启动服务的w / o具有供给须藤密码? An example application of where this is useful is stopping and restarting the NetworkManager
service.这很有用的一个示例应用程序是停止和重新启动
NetworkManager
服务。
#!/bin/python3
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.is_active()
Works for me just as your script is.就像你的脚本一样对我有用。 It's like your question has a solution in itself.
就好像你的问题本身有一个解决方案。 In the terminal, you can start, stop, restart a service with the following command example: sudo systemctl restart "name of service".service.
在终端中,您可以使用以下命令示例启动、停止、重新启动服务:sudo systemctl restart "name of service".service。 To achieve the same via python script, the above command example becomes: /bin/systemctl restart "name of service".service
为了通过 python 脚本实现相同的功能,上面的命令示例变为: /bin/systemctl restart "name of service".service
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.