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

最近比较烦,mongo服务总是因为进程较多挂掉,程序一直报错,搞的我心情很差,于是静下心来找了下资料,用python写了个简单的判断服务的脚本

# 导入
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'))

posted @ 2021-12-20 19:18  love_water  阅读(481)  评论(3)    收藏  举报