Example of using python to monitor windows Services and automatically start services

Source: Internet
Author: User
This article describes how to monitor and automatically start a windows service using python. For more information, see Python 2.7 + pywin32 + wxpython.

Check whether the service is stopped at intervals. if the service is stopped, try to start the service. Service stop logging

AppMain. py

The Code is as follows:


#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

"""
1. Check the service status every minute.
2. if the service status has been stopped, try to start the service.
3. automatically record logs
4. display the taskbar icon
"""

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 );

# Check whether 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 t Exception, e:
Logging. error (e );
Return flag;

# Enable the 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 t Exception, e:
Logging. error (e );

# Exit
Def close (self ):
Try:
If self. scm:
Win32service. CloseServiceHandle (self. scm );
Except t Exception, e:
Logging. error (e );

# Initialization 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 execution started ');

# 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 a window
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] stopped '% (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 ):
# Initialization Configuration
Xml = XmlNode ();
If not xml. LoadFile (C_CONFIG_PATH ):
Logging. error ('configuration 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 ('service'). GetChildrenList (tag = 'item ');
If len (services) = 0:
Logging. error ('monitoring service list cannot be blank ');
Return False;
Self. taskbar = TaskIcon ();
Self. frame = Frame (timelen, services );
Return True;

Def OnExit (self ):
Logging. error ('Stop monitoring 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 operation 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;

# Loading XML files
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 t Exception, e:
Logging. error ("loading XML files failed ");
Logging. error (e. _ str __());
Return flag;

# Loading 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 t Exception, e:
Logging. error ("loading XML content failed ");
Logging. error (e. _ str __());
Return flag;

# Check whether the data is correctly loaded
Def IsLoad (self ):
Return self. currentNode is not None and self. rootNode is not None;

# Return the Root Node object
Def GetRoot (self ):
Return XmlNode (self. rootNode, self. rootNode );

# Search for a node, starting with "/" and starting from the root node; otherwise, search for the node from the 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 );

# Search for 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];

# Retrieve the subnode 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;

# Retrieve the subnode 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;


# Obtain the Map table of a subnode
# KeyType 1 use Attribute Value 2 use a subnode
# KeyName Attribute Value Name or subnode name
# ValueType 1 use Attribute Value 2 use a subnode
# ValueName Attribute Value Name or subnode 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;

# Obtain the node name
Def GetTag (self ):
If self. currentNode is None: return "";
Return self. currentNode. tag;

# Retrieving 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 t 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;
Failed t 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;
Failed t 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 attributes
Def GetAttrs (self, default = {}):
Return XmlAttr (self );

Class XmlAttr (object ):

Def _ init _ (self, node ):
Self. node = node;
Self. InitAttrs ();

# Getting a Node
Def GetNode (self ):
Return self. node;

# Set Node
Def SetNode (self, node ):
Self. node = node;
Self. InitAttrs ();

# Initialize the Node attribute list
Def InitAttrs (self ):
If self. node is None or self. node. currentNode is None:
Self. attrs = {};
Self. attrs = self. node. currentNode. attrib;

# Retrieving attributes
Def GetAttrs (self ):
If self. attrs is None: self. InitAttrs ();
Return self. attrs;

# Retrieving specified attributes
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 ();
Failed t 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;
Failed t 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;
Failed t 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. xml ");
Print node. FindNode ("engine/headers"). GetChildrenMap ("header", XmlNodeMap. ATTR, "name", XmlNodeMap. TEXT, None, XmlNodeValue. STRING );

AppResource. py

The Code is as follows:


#----------------------------------------------------------------------
# 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/fwxff42vmnt452ayrcruuzd8zevh5r8twlhyp2pgv5366sk7wba"
"R5hatc2clyoaj2skxmegtgxucm2dz65kvc5e0ti44vga1_fpl + 6c9 + rqpqJiRXfB8kj4NWVF"
"XdGjxUJsPSFl + samples"
"+ FWJSBOw/4oICBGuNE2JlOC6Ett2yOctbDvPunmj4TbPQGSzgB9cBdTTdXp1uMCYFQ61zUTg"
"KlUthCj1BbW7am8o + zewdmm0buztwjrzzlm5crkchaeui2omejkmmglip8hmela1ihsucqc"
"SsNMFzwXgXg8XlC9oHJF0201jz29ff3NicUBw9Xz6HvDmP/OnImAi + M4OI5Dc6tJIG1DJg2O"
"A5aF1HWEqiEVBXSNYJF6/YP3iyfyrsLoqHHi1CnRMzam9Q4PpyallN45Ao2ts2984BfrX2hd"
"1xbnre7vth1_rjgk7cpazjf9hfjf5 + J53m4rosis1SZ78BXe07f3D5NAF1HNsyFW + 6A + jRP"
"66/OJ8BvpGGQMSsZGSmxjhwJDXzyaW7H/Pllvz14cLRbA/CFQwULb21prZgd00zGAZBIAMyC"
"Province"
"0bqwtv6mmyP1PUemvwa6FYCuPV27Ptr + 0b6cM41DHldaeNLB8zzG5RFy0V6WXFeE61nkciae"
"LUGdEuROSTJZF9vOIR + OI9eVIM3XYOgpsPoRngQPkC6QB0xgioH + Y5OHDg3uOFeEUkrz3fZ /"
"PfNFZ/d0Xk5jk8FxLVzXxbQz7E7/BX9E0NxcAeTIuy65EwrmlMdEDvJrJKwewerbhte3Faw0"
"WgNcwAFcG + QUgglcd5gdOw7t7emZ6r5ABUOHkx9t + 3xhc2mda-17ezwdzfpzl4tg2a85 + PrG3"
"EIxEKC + vJItCctQif3KadAh8yyH9RZrcQBLXOc + xAzgSLMBLIeUox3r7ctu3D7dLKZ0LVCCl"
"9IQQvwqWi9oVTzZt9BWpimVZ2LaNZec4bLxGf3CYSGADmq + Ifd4cbpruIN8CUxkYnAqRLi1D"
"L6mm0EhQiEbMO4phf45QMiA8PHWSP/0xtWPXLue9i2R4hoTVGA + 01 ziBexp + + lBBpqyICX2Y"
"UXWAEaWfZMUHHDc + xlewiC4ZpUmLUjFh88aHCoe/W0 + kpJTy + CwS2gJm6dfgUUzIGUA1nyeQ"
"FY8/v + mNbX7Z + aGUMneu55y/D4SFKH1xef2 + H1xVWIsQWEtXkWtbyWiZxrBxjBHvc0bHviL1"
"WT + xLb08GCojsmQOf + 3o4pkNxRRFkhQF/cQDAaKBMMXhckrCVRT442S/3O09 // jHTxw5kNp8"
"Province"
"Yx + hsuofFJa8RSygEwoE8Pv9BINBfD4fhuHjy3dGxt58unPVeN/k5xeloD4anP/QtZX3 + gKA"
"O4MMguuh2Db + 5Ai + 1DThlMnJLFBTQXFFkNHFfSjNaSb3BrCH8tTVPkGJv5op7TU0TcMwDHRd"
"X + fz4fcFuP7ellJnwtceCoXWZDKZ5AUqWD4nsrE54Y + hu6bj8olggk1_ug6aiaqrs1itkl"
"JbhLPQLNLtFrBY0tJxkatxhJmtxY9gD1keWOpmlomoau6 + i6jqEG8Ysoy9YtbW373sIfn/Wr"
"Nm1_u0fq4mhczolqnd6qmk6acqogqiggvkdpfhvm4wyo4sysj9acir/EcHYLHL + GP/sStHd"
"B7Gs + EEnqEcsRVFQVRVN1dFFAEOEiccrlFUbb99YPae6 + VwKEuVaja5TnnMd/IqKUDxQJCgC"
"HAKlcVh9D + KqEGQ2Q + gomidRbUC/g4w3D4JBpKrywoenaCgv14pDcycnlcPFiqKgCBUFDVXq"
"Platform + C"
"ABIcEA5gBHBFG1 + dKoVAEDSVMU/huz1z7fvl5qrl5iu4lfkrsksumkkkch/YcONH9Qc/rfUcG"
"Province"
"1TfS19VvCQYCPiU37lqTffZnQwcm/z50ILltsGe874Jx/I1mZHJ6aiSFEAPTHh6hM + u4BFwB"
"NqBKUErZ + mWeHjMCAQM0DVQVhKBrZ0rr + smeNbjuYSB5fvM53y6750spzeOjvl60QtCKQI + C"
"ZwA/CL + gN1fOpo + j4PMjAn4CQR/xoEZxUCMgbAtXOyyl7Ptvzi8ZgW9aV5e/I29VN/h8GmAh"
"MULoJxlJZryH2hvMZCwUVgIGUb9K3BBENNAUGMiOJbPkT850/owvnc5O9/VDh6KWpAZJAijj"
"AG/Ue26T8ru9L/1tJfte6QliUeITVPihOihJaFm0ycF9wGVX8m9FYP/+ 9 Kfvv +/scN1qTLOU"
"T97yhh95JP1YZ2frk/Zo375oxzNL3C0P/FJ2vT0cyY95lX5JdKrXccd6tp0ttMvZRSq4lK1a"
"Maid"
"ZyOlFFJK9cz/kh + gAkUvvvii73I4KaWor6/3hcPhkplwZ31 + qwj8L + 0/pB1WIoQcFx8AAAAA"
"SUVORK5CYII = ")

Config. xml

The Code is as follows:






Dhcp


10

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.