python实现监控windows服务并自动启动服务示例_python

使用Python 2.7 + pywin32 + wxpython开发

每隔一段时间检测一下服务是否停止,如果停止尝试启动服务。进行服务停止日志记录

AppMain.py

复制代码 代码如下:

#!/usr/bin/env python
#-*- encoding:utf-8 -*-

"""
1. 每隔一分钟检测一次服务状态
2. 如果发现服务状态已经停止,那么尝试启动服务
3. 自动记录日志
4. 任务栏图标显示
"""

import sys;
reload(sys);
sys.setdefaultencoding('utf-8');

import win32service;
import logging;
from logging.handlers import RotatingFileHandler;
import os.path;
import wx;
import AppResource;
import webbrowser;
from AppXml import *;

C_APP_NAME = "Service Moniter 1.0";
C_LOG_DIR = os.path.altsep.join([os.path.curdir,'service.log']);
C_CONFIG_PATH = os.path.altsep.join([os.path.curdir,'config.xml']);
C_LOG_SIZE = 1048576;
C_LOG_FILES = 3;

C_APP_SITE = "http://www.du52.com/?app=service_moniter&version=1.0.0";

class ServiceControl(object):

    def __init__(self):
        self.scm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS);

    # 检查服务是否停止
    def isStop(self,name):
        flag = False;
        try:
            handle = win32service.OpenService(self.scm,name,win32service.SC_MANAGER_ALL_ACCESS);
            if handle:
                ret = win32service.QueryServiceStatus(handle);
                flag = ret[1]!=win32service.SERVICE_RUNNING;
                win32service.CloseServiceHandle(handle);
        except Exception,e:
            logging.error(e);
        return flag;

    # 开启服务
    def start(self,name):
        try:
            handle = win32service.OpenService(self.scm,name,win32service.SC_MANAGER_ALL_ACCESS);
            if handle:
                win32service.StartService(handle,None);
                win32service.CloseServiceHandle(handle);
        except Exception,e:
            logging.error(e);

    # 退出
    def close(self):
        try:
            if self.scm:
                win32service.CloseServiceHandle(self.scm);
        except Exception,e:
            logging.error(e);

# 初始化日志
def InitLog():
    logging.getLogger().setLevel(logging.ERROR);
    RtHandler = RotatingFileHandler(filename=C_LOG_DIR,maxBytes=C_LOG_SIZE,backupCount=C_LOG_FILES);
    RtHandler.setLevel(logging.ERROR);
    RtHandler.setFormatter(logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s'));
    logging.getLogger().addHandler(RtHandler);
    logging.error('监控开始执行');

# 系统托盘图标
class TaskIcon(wx.TaskBarIcon):

    def __init__(self):
        wx.TaskBarIcon.__init__(self);
        self.SetIcon(AppResource.TaskIcon.getIcon(),C_APP_NAME);
        self.ID_NAME = wx.NewId();
        self.ID_EXIT = wx.NewId();
        self.ID_AUTHOR = wx.NewId();
        self.Bind(wx.EVT_MENU,self.OnExitEvent,id=self.ID_EXIT);
        self.Bind(wx.EVT_MENU,self.OnHelpEvent,id=self.ID_AUTHOR);

    def OnHelpEvent(self,event):
        webbrowser.open_new(C_APP_SITE);

    def OnExitEvent(self,event):
        wx.Exit();

    def CreatePopupMenu(self,event=None):
        menu = wx.Menu();
        menu.Append(self.ID_NAME,C_APP_NAME);
        menu.AppendSeparator();
        menu.Append(self.ID_AUTHOR,"技术支持");
        menu.Append(self.ID_EXIT,"退出");
        return menu;

# 隐藏窗口
class Frame(wx.Frame):

    def __init__(self,timelen,services):
        wx.Frame.__init__(self,parent=None,title=C_APP_NAME);
        self.timelen = timelen*1000;
        self.services = services;
        self.Show(False);
        self.Bind(wx.EVT_TIMER,self.OnTimerEvent);
        self.Bind(wx.EVT_CLOSE,self.OnExitEvent);
        self.timer = wx.Timer(self);
        self.timer.Start(self.timelen);

    def OnTimerEvent(self,event):
        sc = ServiceControl();
        for name in self.services:
            print name;
            if sc.isStop(name):
                logging.error('系统检测到服务[%s]停止'%(name,));
                sc.start(name);
        sc.close();

    def OnExitEvent(self,event):
        if self.timer:
            self.timer.Stop();
            self.timer = None;

# 进程
class Application(wx.App):

    def OnInit(self):
        # 初始化配置
        xml = XmlNode();
        if not xml.LoadFile(C_CONFIG_PATH):
            logging.error('配置文件不存在');
            return False;
        timelen = xml.FindNode('time').GetInt();
        if timelen<=0:
            logging.error('监控间隔时间必须大于0秒');
            return False;
        services = xml.FindNode('services').GetChildrenList(tag='item');
        if len(services)==0:
            logging.error('监控服务列表不能为空');
            return False;
        self.taskbar = TaskIcon();
        self.frame = Frame(timelen,services);
        return True;

    def OnExit(self):
        logging.error('监控停止执行');
        self.frame.Close();
        self.taskbar.RemoveIcon();
        self.taskbar.Destroy();

if __name__ == '__main__':
    InitLog();
    app = Application();
    app.MainLoop();

AppXml.py

复制代码 代码如下:

#!/usr/bin/env python
#-*- encoding:utf-8 -*-

"""
XML操作封装
"""

import os.path;
import logging;
import xml.etree.ElementTree as ElementTree;

class XmlNodeValue(object):
    STRING = 1;
    INT = 2;
    FLOAT = 3;
    BOOL = 4;

class XmlNodeMap(object):
    ATTR = 1;
    TEXT = 2;
    NODE = 3;

class XmlNode(object):

    def __init__(self,currentNode=None,rootNode=None):
        self.currentNode = currentNode;
        self.rootNode = rootNode;

    # 加载XML文件
    def LoadFile(self,path):
        if os.path.isabs(path): path = os.path.abspath(path);
        flag = False;
        try:
            self.rootNode = ElementTree.parse(path);
            if self.rootNode is not None: flag = True;
            self.currentNode = self.rootNode;
        except Exception,e:
            logging.error("XML文件加载失败");
            logging.error(e.__str__());
        return flag;

    # 加载XML内容
    def LoadString(self,data):
        if data is None or len(data.strip())==0: return False;
        flag = False;
        try:
            self.rootNode = ElementTree.fromstring(data);
            if self.rootNode is not None: flag = True;
            self.currentNode = self.rootNode;
        except Exception,e:
            logging.error("XML内容加载失败");
            logging.error(e.__str__());
        return flag;

    #  检查数据是否载入正确
    def IsLoad(self):
        return self.currentNode is not None and self.rootNode is not None;

    # 返回根节点对象
    def GetRoot(self):
        return XmlNode(self.rootNode,self.rootNode);

    # 查找节点,开始为“/”从根节点开始查找,否则从当前节点查找
    def FindNode(self,path):
        if path is None or len(path.strip())==0: return XmlNode(None,self.rootNode);
        path = path.strip();
        node = None;
        if path[0]=='/':
            node = self.rootNode.find(path[1:]);
        else:
            node = self.currentNode.find(path);
        return XmlNode(node,self.rootNode);

    # 查找多节点
    def FindNodes(self,path):
        if path is None or len(path.strip())==0: return XmlNode(None,self.rootNode);
        if path[0]=='/':
            nodes = self.rootNode.findall(path[1:]);
        else:
            nodes = self.currentNode.findall(path);
        return [XmlNode(node,self.rootNode) for node in nodes];

    # 获取子节点列表
    def GetChildrens(self,tag=None):
        return [XmlNode(node,self.rootNode) for node in self.currentNode.iter(tag=tag)];

    # 格式化数据
    def GetFormatData(self,node,type):
        if type==XmlNodeValue.STRING:
            v = node.GetStr();
        elif type==XmlNodeValue.INT:
            v = node.GetInt();
        elif type==XmlNodeValue.FLOAT:
            v = node.GetFloat();
        elif type==XmlNodeValue.BOOL:
            v = node.GetBool();
        else:
            v = node.GetData();
        return v;

    # 获取子节点内容列表
    # valueFormat 值类型 1 字符串,2 整数,3 小数,4 布尔值
    def GetChildrenList(self,tag=None,valueFormat=XmlNodeValue.STRING):
        data = [];
        for node in self.GetChildrens(tag=tag):
            data.append(self.GetFormatData(node,valueFormat));
        return data;

    # 获取子节点Map表
    # keyType 1 使用属性值 2 使用子节点
    # keyName   属性值名称或子节点名称
    # valueType 1 使用属性值 2 使用子节点
    # ValueName 属性值名称或子节点名称
    def GetChildrenMap(self,tag=None,keyType=XmlNodeMap.ATTR,keyName="name",valueType=XmlNodeMap.TEXT,valueName=None,valueFormat=XmlNodeValue.STRING):
        data = {};
        for node in self.GetChildrens(tag=tag):
            k,v = None,None;
            if keyType==XmlNodeMap.ATTR:
                if keyName is None or len(keyName.strip())==0: continue;
                k = node.GetAttrs().GetStr(keyName);
            elif keyType==XmlNodeMap.NODE:
                if keyName is None or len(keyName.strip())==0: continue;
                t = node.FindNode(keyName);
                if not t.IsLoad(): continue;
                k = t.GetStr();
            elif keyType==XmlNodeMap.TEXT:
                k = node.GetStr();
            else:
                continue;
            if k is None or len(k.strip())==0: continue;
            if valueType==XmlNodeMap.ATTR:
                if valueName is None or len(valueName.strip())==0: continue;
                v = self.GetFormatData(node.GetAttrs(),valueFormat);
            elif valueType==XmlNodeMap.NODE:
                if valueName is None or len(valueName.strip())==0: continue;
                t = node.FindNode(valueName);
                if t.IsLoad():
                    v = self.GetFormatData(t,valueFormat);
            elif valueType==XmlNodeMap.TEXT:
                v = self.GetFormatData(node,valueFormat);
            else:
                v = None;
            data[k] = v;
        return data;

    # 获取节点名称
    def GetTag(self):
        if self.currentNode is None: return "";
        return self.currentNode.tag;

    # 获取节点内容
    def GetData(self,default=None):
        if self.currentNode is None: return default;
        return self.currentNode.text;

    def GetStr(self,default="",strip=True):
        data = self.GetData();
        if data is None: return default;
        try:
            data = str(data.encode("utf-8"));
            if data is None:
                data = default;
            else:
                if strip:
                    data = data.strip();
        except Exception,e:
            print e;
            data = default;
        return data;

    def GetInt(self,default=0):
        data = self.GetData();
        if data is None: return default;
        try:
            data = int(data);
            if data is None: data = default;
        except Exception:
            data = default;
        return data;

    def GetFloat(self,default=0.0):
        data = self.GetData();
        if data is None: return default;
        try:
            data = float(data);
            if data is None: data = default;
        except Exception:
            data = default;
        return data;

    def GetBool(self,default=False):
        data = self.GetData();
        if data is None: return default;
        data = False;
        if self.GetStr().lower()=="true" or self.GetInt()==1: data = True;
        return data;

    # 获取节点属性
    def GetAttrs(self,default={}):
        return XmlAttr(self);

class XmlAttr(object):

    def __init__(self,node):
        self.node = node;
        self.InitAttrs();

    # 获取Node
    def GetNode(self):
        return self.node;

    # 设置Node
    def SetNode(self,node):
        self.node = node;
        self.InitAttrs();

    # 初始化Node属性列表
    def InitAttrs(self):
        if self.node is None or self.node.currentNode is None:
            self.attrs = {};
        self.attrs = self.node.currentNode.attrib;

    # 获取属性
    def GetAttrs(self):
        if self.attrs is None: self.InitAttrs();
        return self.attrs;

    # 获取指定属性
    def GetData(self,key,default=None):
        data = self.attrs.get(key);
        if data is None : data = default;
        return data;

    def GetStr(self,key,default="",strip=True):
        data = self.GetData(key);
        if data is None: return default;
        try:
            data = str(data.encode("utf-8"));
            if data is None:
                data = default;
            else:
                if strip:
                    data = data.strip();
        except Exception:
            data = default;
        return data;

    def GetInt(self,key,default=0):
        data = self.GetData(key);
        if data is None: return default;
        try:
            data = int(data);
            if data is None: data = default;
        except Exception:
            data = default;
        return data;

    def GetFloat(self,key,default=0.0):
        data = self.GetData(key);
        if data is None: return default;
        try:
            data = float(data);
            if data is None: data = default;
        except Exception:
            data = default;
        return data;

    def GetBool(self,key,default=False):
        data = self.GetData(key);
        if data is None: return default;
        data = False;
        if self.GetStr(key).lower()=="true" or self.GetInt(key)==1: data = True;
        return data;

# 测试
if __name__ == "__main__":
    node = XmlNode();
    print node.LoadFile(r"config.xml");
    print node.FindNode("engine/headers").GetChildrenMap("header",XmlNodeMap.ATTR,"name",XmlNodeMap.TEXT,None,XmlNodeValue.STRING);

AppResource.py

复制代码 代码如下:

#----------------------------------------------------------------------
# This file was generated by C:\Python27\Scripts\img2py
#
from wx.lib.embeddedimage import PyEmbeddedImage

TaskIcon = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAACQdJ"
    "REFUWIXFl31s1eUVxz/P7+2+997evve2pZbaQmmhCOIL9QVBgsjEGSMZOHRGjTFmWcymy7Ko"
    "WcKy+YeJy7Kha4zMbWEO4xadSp0EQQiiFUeLopTSN9rblkLbe+/v3vt7e/YHLwFh1IQsO8kv"
    "v3++ec73Oed8zzmPkFIK/o+mzAQQQigNDQuWxGKxWiHEjPhQSJRXFfjqvy0BbSZAbW1j/f33"
    "/+ztUCie6+z8cG9NTUv74GD3LimldT4uJkTstpbCR7esu/rhZCaXjgixMiXliSsmkEg0rZjf"
    "sqI4GIpTV3fLfYsXrV+za/fWXfF42VMnT452AyRCRuuzd8zevH5R8TWlhYp2PGV5H7Sk7wba"
    "r5hATc2ClYoaJ2sKXMegtGxucM2dz65KVC5e0ti44vGa3Gfpl+6c9+rqpqJiRXfB8kj4NWVF"
    "XdGjxUJsPSFl+ooIRMKJ5qwp8CS4jsSywLY9Zs9eFheO03732LPW8lklceEIQIDrIYTkhorC"
    "+fWJSBOw/4oICBGuNE2JlOC6Ett2yOctbDvPunmj4TbPQGSzg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FwB"
    "NqBKUErZ+mWeHjMCAQM0DVQVhKBrZ0rr+smeNbjuYSB5fvM53y6750spzeOjvl60QtCKQI+C"
    "zwA/CL+gN1fOpo+j4PMjAn4CQR/xoEZxUCMgbAtXOyyl7Ptvzi8ZgW9aV5e/I29VN/h8GmAh"
    "mULoJxlJZryH2hvMZCwUVgIGUb9K3BBENNAUGMiOJbPkT850/owvnc5O9/VDh6KWpAZJAijj"
    "aG/Ue26T8ru9L/1tJfte6QliUeITVPihOihJaFm0ycF9wGVX8m9FYP/+9Kfvv+/scN1qTLOU"
    "t97yhh95JP1YZ2frk/Zo375oxzNL3C0P/FJ2vT0cyY95lX5JdKrXccd6tp0ttMvZRSq4lK1a"
    "NXf1hg3znz94MHkwna57de3adX2qqiqu6yoAlmXR0bGjqmss1xasbrneS08qHS///F4p5eRM"
    "ZyOlFFJK9cz/kh+gAkUvvvii73I4KaWor6/3hcPhkplwZ31+qwj8L+0/pB1WIoQcFx8AAAAA"
    "SUVORK5CYII=")

config.xml

复制代码 代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<config>
    <!-- 需要监控的服务名称列表 -->
    <services>
        <item>Dhcp</item>
    </services>
    <!-- 间隔时间(单位秒) -->
    <time>10</time>
</config>

时间: 2024-10-26 12:04:24

python实现监控windows服务并自动启动服务示例_python的相关文章

利用Python自动监控网站并发送邮件告警的方法_python

前言 因为有一些网站需要每日检查是否有问题,所以需要一个报警监控的机制,这个需要你指定你发送的邮箱和你接收的邮箱,就可以做到对网站自动监控了. 这里用的是python3.5 需要安装的插件:       1.smtplib:发邮件需要用到       2.pycurl:访问网站时会需要用到       3.linecache:在读取txt网站清单时需要用到 具体思路: python程序从txt里面批量读取到网站的信息,通过Curl.py模拟浏览器去访问网站,并且把访问的结果写入到以自己的网站名称

Python中捕捉详细异常信息的代码示例_python

大家在开发的过程中可能时常碰到一个需求,需要把Python的异常信息输出到日志文件中. 网上的办法都不太实用,下面介绍一种实用的,从Python 2.7源码中扣出来的. 废话不说 直接上代码,代码不多,注释比较多而已. import sys, traceback traceback_template = '''Traceback (most recent call last): File "%(filename)s", line %(lineno)s, in %(name)s %(ty

windows下python模拟鼠标点击和键盘输示例_python

需要先装pywin32,windows下调用winapi的接口 复制代码 代码如下: ## _*_ coding:UTF-8 _*___author__ = 'shanl' import win32apiimport win32conimport win32guifrom ctypes import *import time VK_CODE = {    'backspace':0x08,    'tab':0x09,    'clear':0x0C,    'enter':0x0D,    '

python实现数通设备tftp备份配置文件示例_python

  环境:[wind2003[open Tftp server] + virtualbox:ubuntn10 server]tftp : Open TFTP Server   ubuntn  python + pyexpect 采用虚拟机原因: pyexpect 不支持windows  注:原打算采用secrueCrt 脚本编写,因实践中发现没有使用linux下pexpect易用,灵活  ,之前习惯使用expect,因tcl[语法]没有python易用.易维护 编写些程序原因:最近出了比较严重故

Python实现生成简单的Makefile文件代码示例_python

在linux下写几个测试程序,还要一行行的输入g++命令进行编译,当经常改测试代码的时候,那一次次的敲(或者一次次的上线箭头选)也感觉不爽,不如make来的快.用Makefile的好处就不用多说了,这里我写了个脚本,其功能是自动搜索当前目录(不包括子目录)下的".c"文件生成Makefile文件. 代码在这里,功能有限(适用于单个文件是一个独立的测试代码的情况),需要的朋友可以稍作修改以满足需求. 复制代码 代码如下: #! /usr/bin/python '''  File     

Python和GO语言实现的消息摘要算法示例_python

常用的消息摘要算法有MD5和SHA,这些算法在python和go的库中都有,需要时候调用下就OK了,这里总结下python和go的实现. 一.python消息摘要示例 代码如下: 复制代码 代码如下: #! /usr/bin/python '''       File      : testHash.py       Author    : Mike       E-Mail    : Mike_Zhang@live.com ''' import hashlib src = raw_input(

使用Python读写及压缩和解压缩文件的示例_python

读写文件首先看一个例子: f = open('thefile.txt','w') #以写方式打开, try: f.write('wokao') finally: f.close() 文件的打开方式: f = open('文件','mode') 'r':只读(缺省.如果文件不存在,则抛出错误) 'w':只写(如果文件不存在,则自动创建文件),此时无法调用f.read()方法,且当调用f.write()时,将清空文件原有内容 'a':附加到文件末尾 'r+':读写 如果需要以二进制方式打开文件,需要

Python的collections模块中namedtuple结构使用示例_python

namedtuple 就是命名的 tuple,比较像 C 语言中 struct.一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 访问,没有明确的称呼,而 namedtuple 就是事先把这些 item 命名,以后可以方便访问. from collections import namedtuple # 初始化需要两个参数,第一个是 name,第二个参数是所有 item 名字的列表. coordinate = namedtu

python正则表达式判断字符串是否是全部小写示例_python

复制代码 代码如下: # -*- coding: cp936 -*-import re  s1 = 'adkkdk's2 = 'abc123efg' an = re.search('^[a-z]+$', s1)if an:    print 's1:', an.group(), '全为小写' else:    print s1, "不全是小写!" an = re.match('[a-z]+$', s2)if an:    print 's2:', an.group(), '全为小写'