python - 如何通过不需要 sudo 密码的 python 脚本停止和启动 systemd 服务
问题描述
以下脚本允许我检查 asystemd service
是否处于活动状态,并停止或启动服务。执行.stop()
or.start()
时,如何在无需提供 sudo 密码的情况下直接停止和启动服务?一个有用的示例应用程序是停止和重新启动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()
解决方案
就像你的脚本一样为我工作。就像您的问题本身就有解决方案一样。在终端中,您可以使用以下命令示例启动、停止、重新启动服务:sudo systemctl restart "name of service".service。为了通过 python 脚本实现相同的功能,上面的命令示例变为: /bin/systemctl restart "name of service".service
推荐阅读
- crystal-reports - Crystal Report:如何在背景水印图像上显示线条?
- react-native - 错误:auth / session-expired 短信代码已过期。请重新发送验证码重试
- c++ - 制作自定义 Csv 文件管理器类时未创建 std::fstream 文件
- typescript - 有人能解释一下为什么使用 es6 语法和 es5 和 typescript 在 Leetcode 上的速度存在巨大差异吗?
- python - 从 Python 中的现有列创建新列
- docker-compose - Docker-compose FastAPI --reload
- c++ - 在为每个循环迭代向量时更新向量值
- flutter - Flutter ToggleButtons - 断言失败:'children.length == isSelected.length':不正确
- c# - 捕获服务器响应并将其显示到屏幕 angular/c#
- javascript - 如何使用 PHP 在 jquery 中获取分页的活动页码