python实现监控windows服务控制开关服务
转载自 :http://www.jb51.net/article/49106.htm
#!/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();
python实现监控windows服务控制开关服务的更多相关文章
- Nagios 监控windows server Apache 服务
监控机需要使用check_apachestatus.pl插件插件下载地址:https://exchange.nagios.org/directory/Tutorials/Other-Tutorials ...
- 监控windows服务,当服务停止后自动重启服务
近期花时间研究了一下windows和linux下某服务停了后自动重启的功能,在网上收集了些资料,并经过测试,在此整理一下.这里介绍的是windows服务的监控,是通过批处理来实现的.本例是监控wind ...
- python实现编写windows服务
使用python编写windows服务 最近测试服务器上经常发生磁盘空间不足,每次手动清除比较麻烦,所以写个windows服务定时清理下.中间也遇到过几个坑,一起记录下来. 1.python实现win ...
- C#代码安装、卸载、监控Windows服务
C#编写Windows服务之后都不可避免的需要安装,卸载等操作.而传统的方式就是通过DOS界面去编写命令,这样的操作方式无疑会增加软件实施人员的工作量,下面就介绍一种简单.高效.快速方便的方式.1.安 ...
- 宣布正式发布 Windows Azure 移动服务、网站及持续的服务创新
我们努力创新,向开发人员提供多样化平台以构建最好的云应用程序并在第一时间提供给世界各地的客户.许多新应用程序都属于"现代化应用程序",即始终基于 Web,且可以通过各种移动设备进行 ...
- Centos7.6上部署Supervisor来监控和操作各类服务
supervisor 是用Python开发的一个client/server服务,是Linux/Unix系统下的一个进程管理工具,不支持Windows系统.它可以很方便的监听.启动.停止.重启一个 ...
- C#/.NET基于Topshelf创建Windows服务程序及服务的安装和卸载(极速,简洁)
本文首发于:码友网--一个专注.NET/.NET Core开发的编程爱好者社区. 文章目录 C#/.NET基于Topshelf创建Windows服务的系列文章目录: C#/.NET基于Topshelf ...
- python os.startfile python实现双击运行程序 python监控windows程序 监控进程不在时重新启动
用python监控您的window服务 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://world77.blog.51cto.co ...
- 【数据库开发】在Windows上以服务方式运行 MSOPenTech/Redis
在Windows上以服务方式运行 MSOPenTech/Redis ServiceStack.Redis 使用教程里提到Redis最好还是部署到Linux下去,Windows只是用来做开发环境,现在这 ...
随机推荐
- 洛谷 P2463 [SDOI2008]Sandy的卡片 解题报告
P2463 [SDOI2008]Sandy的卡片 题意 给\(n(\le 1000)\)串,定义两个串相等为"长度相同,且一个串每个数加某个数与另一个串完全相同",求所有串的最长公 ...
- CodeChef题目选讲
https://wenku.baidu.com/view/2445a0322f60ddccda38a023.html 关键点:不超过7条 根据咕咕原理,所以答案最少是N/7;(N小于49就暴力) 随机 ...
- 洛谷P3195 玩具装箱TOY
题目大意: 有n个数,要将他们分成若干段,每一段的cost定义为: cost=r-l+ΣCk (k∈[r,l]) 该段的最终花费是:(cost-L)^2; 给出L,n,C(1~n),总共的最小花费. ...
- A1050. String Subtraction
Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the ...
- 1063. Set Similarity
Given two sets of integers, the similarity of the sets is defined to be Nc/Nt*100%, where Nc is the ...
- javascript面向对象精要第一章原始类型和引用类型整理精要
- hdu4549_M斐波那契数列 解题报告
Solution: 1.快速幂:数/矩阵 2.以证明1000000007是素数. 费马小定理: 若p是素数,gcd(a,p)=1,则a^(p-1)1(mod p). 若a^b mod p 中b很大,则 ...
- instance of
instanceof是Java的一个二元操作符(运算符),也是Java的保留关键字.它的作用是判断其左边对象是否为其右边类的实例,返回的是boolean类型的数据.用它来判断某个对象是否是某个Clas ...
- SQL Server 日期函数大全
一.统计语句 1.--统计当前[>当天00点以后的数据] SELECT * FROM 表 WHERE CONVERT(Nvarchar, dateandtime, 111) = CONVERT( ...
- 启动tomcat时报错:java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException:A child container failed during start
解决方法:https://www.cnblogs.com/xiangxinhouse/p/6377842.html