averainy's Blog

averainy

08 Nov 2022

使用python监控systemd服务修改版

以前写过一个监控systemd service的脚本,在使用过程中发现了一些问题,比如service不存在时,或者service状态是 **Active: active (exited)**的时候会误认为service未启动,因此做了一下修正。 代码如下:

# -*- coding: utf-8 -*-
import logging
import subprocess
from subprocess import check_output,run
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)  # 设置全局日志level,不设置默认WARN

# save log to file
file_handler = logging.FileHandler("/tmp/test.log")
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
        '%(asctime)s: %(levelname)s: '
        '[%(filename)s: %(lineno)d]: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler.setFormatter(formatter)

# print to screen
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)

# add handlers to logger
logger.addHandler(file_handler)
logger.addHandler(stream_handler)

def is_active(service):
    """ 返回服务的主进程 PID """
    cmd = 'systemctl is-active %s' % service
    #output = check_output(cmd, shell=1).decode('utf8')
    output = subprocess.getoutput(cmd)
    if output.strip() == "active":
        return True
    else:
        return False
def check_service(service):
    if is_active(service):
        logger.debug("{0} is active".format(service))
        return
    cmd = ["systemctl","start",service]
    ret = subprocess.run(cmd)
    if ret.returncode == 0:
        logger.debug("success:",ret)
    else:
        logger.debug("error:",ret)



if __name__ == '__main__':
    check_service("wg-quick@wg0")

本文完。