簡體   English   中英

如何通過不需要sudo密碼的python腳本停止和啟動systemd服務

[英]How to stop and start a systemd service via python script w/o requiring sudo password

以下腳本允許我檢查systemd service是否處於活動狀態,以及停止或啟動該服務。 當執行.stop().start()如何繼續進行到停止和直接啟動服務的w / o具有供給須藤密碼? 這很有用的一個示例應用程序是停止和重新啟動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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM