python监控windows服务判断是否终止

453 阅读1分钟

python监控windows服务判断是否终止

# 导入
from __future__ import print_function
import psutil
# 获取服务状态
def get_service(name):
    service = None
    try:
        service = psutil.win_service_get(name)
        service = service.as_dict()
    except Exception as ex:
        print(str(ex))
    return service
# 判断windows服务是否停止,如果停止则启动
def is_service_running_or_start(name):
    service = get_service(name)
    if service and service['status'] == 'running':
        return "{}:Service is running".format(name)
    else:
        try:
            psutil.win_service_start(name)
            return "{}:Service is running".format(name)
        except Exception as ex:
            return "{}:Service is not running".format(name)
print(is_service_running_or_start('MongoDB'))