Python implements monitoring Windows services and automatically starts the service sample

Source: Internet
Author: User
Developed with Python 2.7 + Pywin32 + Wxpython

Every once in a while to detect if the service is stopped, if you stop trying to start the service. Perform service Stop logging

appmain.py

The code is as follows:


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

"""
1. Check service status every minute
2. If the service status is found to be stopped, try to start the service
3. Automatic log logging
4. Taskbar icon Display
"""

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: ']);
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);

# Check if the service is stopped
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;

# Open Service
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);

# exit
def close (self):
Try
If SELF.SCM:
Win32service. Closeservicehandle (SELF.SCM);
Except Exception,e:
Logging.error (e);

# Initialize Log
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 (' monitoring starts execution ');

# System tray icon
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, "technical support");
Menu. Append (Self.id_exit, "exit");
return menu;

# Hide Windows
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 (' System detected service [%s] stop '% (name,) ');
Sc.start (name);
Sc.close ();

def onexitevent (self,event):
If Self.timer:
Self.timer.Stop ();
Self.timer = None;

# process
Class Application (WX. APP):

def OnInit (self):
# Initialize Configuration
XML = XmlNode ();
If not XML. LoadFile (C_config_path):
Logging.error (' config file does not exist ');
return False;
Timelen = XML. FindNode (' time '). GetInt ();
If timelen<=0:
Logging.error (' monitoring interval must be greater than 0 seconds ');
return False;
Services = XML. FindNode (' Services '). Getchildrenlist (tag= ' item ');
If Len (services) ==0:
Logging.error (' The Monitoring Service list cannot be empty ');
return False;
Self.taskbar = Taskicon ();
Self.frame = FRAME (timelen,services);
return True;

def OnExit (self):
Logging.error (' monitoring Stop Execution ');
Self.frame.Close ();
Self.taskbar.RemoveIcon ();
Self.taskbar.Destroy ();

if __name__ = = ' __main__ ':
Initlog ();
App = Application ();
App. Mainloop ();

appxml.py

The code is as follows:


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

"""
XML Operations Encapsulation
"""

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;

# Load XML file
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 file failed to load");
Logging.error (e.__str__ ());
return flag;

# Load XML content
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 content failed to load");
Logging.error (e.__str__ ());
return flag;

# Check that the data is loaded correctly
def isload (self):
Return Self.currentnode are not none and self.rootnode are not none;

# Returns the root node object
def getroot (self):
Return XmlNode (Self.rootnode,self.rootnode);

# Find node, start looking for "/" from root node, otherwise find from current node
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);

# Find multiple nodes
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];

# Get child node list
def getchildrens (Self,tag=none):
return [XmlNode (Node,self.rootnode) for node in Self.currentNode.iter (Tag=tag)];

# Formatting data
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;

# Get child node content list
# Valueformat value type 1 string, 2 integer, 3 decimal, 4 Boolean
def getchildrenlist (self,tag=none,valueformat=xmlnodevalue.string):
data = [];
For node in self. Getchildrens (Tag=tag):
Data.append (self. Getformatdata (Node,valueformat));
return data;


# Get child Nodes map table
# keyType 1 Using the attribute value 2 with child nodes
# KeyName Property Value name or child node name
# valueType 1 Using the attribute value 2 with child nodes
# ValueName Property Value name or child node name
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;

# Get node Name
def gettag (self):
If Self.currentnode is None:return "";
return self.currentNode.tag;

# Get node Content
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;

# Get Node Properties
def getattrs (self,default={}):
return xmlattr (self);

Class Xmlattr (object):

def __init__ (Self,node):
Self.node = node;
Self. Initattrs ();

# get Node
def getnode (self):
return self.node;

# set Node
def setnode (Self,node):
Self.node = node;
Self. Initattrs ();

# Initialize Node Property list
def initattrs (self):
If Self.node is None or Self.node.currentNode is none:
Self.attrs = {};
Self.attrs = Self.node.currentNode.attrib;

# Get Properties
def getattrs (self):
If Self.attrs is none:self. Initattrs ();
return self.attrs;

# Gets the specified property
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;

# test
if __name__ = = "__main__":
node = XmlNode ();
Print node. LoadFile (r "config");
Print node. FindNode ("Engine/headers"). Getchildrenmap ("header", Xmlnodemap.attr, "name", xmlnodemap.text,none,xmlnodevalue.string);

appresource.py

The code is as follows:


#----------------------------------------------------------------------
# This file is 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/4OICBGUNE2JLOC6ETT2YOCTBDVPUNMJ4TBPQGSZGB9CBDTTDXP1UMCYFQ61ZUTG"
"KLUTHCJ1BBW7AM8O+ZEWDMM0BUZTWJRZZLM5CRKCHAEUI2OMEJKMMGLIP8HMGELA1IHSUCQC"
"Ssnmfzwxgxg8xlc9ohjf0201jz29ff3nicubw9xz6hvdmp/onimai+m4oi5dc6tjig1djg2o"
"A5AF1HWEQIEVBXSNYJF6/YP3IYFYRSLOQHHI1CNRMZAM9Q4PPYALLN45AO2TS2984BFRX2HD"
"1XBNRE7VTHGCRJWGK7CPAZJF9HFJF5+J53M4ROSIS1SZ78BXE07F3D5NAF1HNSYFW+6A+JRP"
"66/oj8bvpggqmsszgsmxjhwjdxzyaw7h/pllvz14clrba/cfqwulb21przgd00zgazbiamyc"
"W7TDTJAX0RTJ41K8ZYPEBKGH3BJHVKZJPXG2BZEG3LCC1M4E0Q9TVYDSDCBCAVYCGQHGEUWB"
"0bqwtv6mmyp1puemvwa6fycupv27ptr+0b6cm41dhldaenlb8zzg5rfy0v6wxfee61nkciae"
"Lugdeurostjzf9voir+oi9evim3xyogpsporngqpkc6qb0xgioh+y5ohdg3uofeeukrz3fz/"
"Pfnfz/d0xk5jk8fxlvzxxbqz7e7/bx9e0nxcaetiuy65ewrmlmdedvjrjkwewerbhte3faw0"
"Wgncwafcg+qugglcd5gdow7t7emz6r5abuohkx9t+3xhc2mjw17ezwdzfpzl4tg2a85+prg3"
"EIXEKC+VJITCCTQIF3KADAH8YYH9RZRCQBLXOC+XAZGSLMBLIEUOX3R7CTU3D7DLKZ0LVCCL"
"9IQQVWQWI9OVTZZT9BWPIMVZ2LANZEC4BLXGF3CYSGADMQ+IFD4CBPRUIN8CUXKYNAQRLI1D"
"L6MM0EHQIEBMO4PHF45QMIA8PHWSP/0XTWPXLUE9I2R4HOTVGA+01ZIBEXP++LBBPQYICX2Y"
"Uxwaeawfzmuhhdc+xlewic4zpumlujfh88ahcoe/w0+kpjty+cws2gjm6dfguuzigua1nyeq"
"Fy8/v+mnbx7z+agumneu55y/d4sfkh1xef2+h1xvwisqwetxkwtbywizxrbxjbhvc0bhvil1"
"Wt+xlb08gcojsmqof+3o4pknxrrfkhqf/cqdaakbmmxhckrcvrt442s/3o09//jhtxw5knp8"
"Qdm7s0aioty6shlzb5y3pexzxmhmijpbs2yscajt7zgdmyq1eir80qxhrcvf6idufwntdiud"
"Yx+hsuoffja8rsygewoe8pv9binbfd4fhuhjy3dgxt58unpven/k5xelod4anp/qtzx3+gka"
"O4MMGUUH2DB+5AI+1DTHLMNJLFBTQXFFKNHFFSJNASB3BRCH8TTVPKGJV5OP7TU0TC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1xasbrnes08qhs///f4p5erm"
"Zyolffjk9cz/kh+gakuvvvii73i4kawor6/3hcphkplwz31+qwj8l+0/pb1wioqcfx8aaaaa"
"Suvork5cyii=")

Config.

The code is as follows:






Dhcp


10

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.