如何通过不带sudo密码的python脚本停止和启动systemd服务

时间:2018-11-08 18:20:35

标签: python service

以下脚本允许我检查systemd service是否处于活动状态,以及停止或启动服务。在执行.stop().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()

1 个答案:

答案 0 :(得分:0)

就像您的脚本一样为我工作。就像您的问题本身就有一个解决方案。 在终端中,可以使用以下命令示例启动,停止,重新启动服务:sudo systemctl restart“服务名称” .service。为了通过python脚本实现相同的功能,上述命令示例变为:/ bin / systemctl restart“服务名称” .service