Windows 服务状态检查(含Linux服务差)

1, window上查询服务的状态

from subprocess import Popen, PIPE
import sys, re, json, socket
from _utils.patrol2 import run_cmd, data_format, report_format
import os, platform,wmi


def getoutput(command):
    p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = p.communicate()
    if err:
        print('command exec error: %s' % command)
        sys.exit(1)
    else:
        return out


def get_process_num(server_name):
    alert = 0
    command = ('ps -ef|grep {} |grep -v grep|head -1|awk \'{print $2}\' | wc - l').format(server_name)
    count = getoutput(command)
    count = int(count)
    if count !=0:
        result = "%s正常!" % server_name
    else:
        alert = 1
        result = "%s异常!" % server_name
    return  data_format('{}服务状态'.format(server_name), result, alert)

def check_server(server_name):
    alert = 1
    value = "%s服务不存在" %server_name
    windos = wmi.WMI()#生成实例
    servers = windos.Win32_Service() 
    print server_name
    for i in servers:
        #print "开始查询"
        if i.Name.encode('utf-8') == '%s'%server_name:  # i.Name 获取服务名  获取的结果是Unicode  需要转码  进行比较  
            if i.State.encode('utf-8') == 'Running':  #i.State 获取服务状态
                alert = 0
                value = "%s 运行中..."%server_name
                print value
            else:
                value = "%s 已停止..."%server_name
                print value
        else:
            pass
    return data_format('服务状态', value, alert)

if __name__ == '__main__':
    if sys.platform.startswith('win'):
        reports = check_server(server_name)
    else:
        reports = get_process_num(server_name)
    hostname = socket.gethostname()
    reports=report_format(hostname,reports,is_json=True)
    print reports

 

posted @ 2020-03-23 17:58  QQmini  阅读(297)  评论(1编辑  收藏  举报