转载自 :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服务控制开关服务的更多相关文章

  1. Nagios 监控windows server Apache 服务

    监控机需要使用check_apachestatus.pl插件插件下载地址:https://exchange.nagios.org/directory/Tutorials/Other-Tutorials ...

  2. 监控windows服务,当服务停止后自动重启服务

    近期花时间研究了一下windows和linux下某服务停了后自动重启的功能,在网上收集了些资料,并经过测试,在此整理一下.这里介绍的是windows服务的监控,是通过批处理来实现的.本例是监控wind ...

  3. python实现编写windows服务

    使用python编写windows服务 最近测试服务器上经常发生磁盘空间不足,每次手动清除比较麻烦,所以写个windows服务定时清理下.中间也遇到过几个坑,一起记录下来. 1.python实现win ...

  4. C#代码安装、卸载、监控Windows服务

    C#编写Windows服务之后都不可避免的需要安装,卸载等操作.而传统的方式就是通过DOS界面去编写命令,这样的操作方式无疑会增加软件实施人员的工作量,下面就介绍一种简单.高效.快速方便的方式.1.安 ...

  5. 宣布正式发布 Windows Azure 移动服务、网站及持续的服务创新

    我们努力创新,向开发人员提供多样化平台以构建最好的云应用程序并在第一时间提供给世界各地的客户.许多新应用程序都属于"现代化应用程序",即始终基于 Web,且可以通过各种移动设备进行 ...

  6. Centos7.6上部署Supervisor来监控和操作各类服务

    supervisor    是用Python开发的一个client/server服务,是Linux/Unix系统下的一个进程管理工具,不支持Windows系统.它可以很方便的监听.启动.停止.重启一个 ...

  7. C#/.NET基于Topshelf创建Windows服务程序及服务的安装和卸载(极速,简洁)

    本文首发于:码友网--一个专注.NET/.NET Core开发的编程爱好者社区. 文章目录 C#/.NET基于Topshelf创建Windows服务的系列文章目录: C#/.NET基于Topshelf ...

  8. python os.startfile python实现双击运行程序 python监控windows程序 监控进程不在时重新启动

    用python监控您的window服务 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://world77.blog.51cto.co ...

  9. 【数据库开发】在Windows上以服务方式运行 MSOPenTech/Redis

    在Windows上以服务方式运行 MSOPenTech/Redis ServiceStack.Redis 使用教程里提到Redis最好还是部署到Linux下去,Windows只是用来做开发环境,现在这 ...

随机推荐

  1. suoi21 高能显示屏 (cdq分治)

    可以把翻倍的操作看作是一个查询和修改(增加刚查询得来的值)的符合操作,然后做cdq就行了 #include<bits/stdc++.h> #define pa pair<int,in ...

  2. CF1114B Yet Another Array Partitioning Task(贪心,构造题)

    我至今不敢相信我被这么一道简单的题卡了这么久……看来还是太弱了…… 题目链接:CF原网 题目大意:定义一个序列的“美丽度”为这个序列前 $m$ 大的数的和.现在有一个长度为 $n$ 的序列,你需要把它 ...

  3. Linux:进程实例信息(/proc)

    https://blog.csdn.net/test1280/article/details/73632333 Linux:进程实例信息(/proc) 问几个问题: 1.怎么知道一个进程对应哪个可执行 ...

  4. Deformable ConvNets

    Deformable ConvNets 论文 Deformable Convolutional Networks(arXiv:1703.06211) CNN受限于空间结构,具有较差的旋转不变性,较弱的 ...

  5. 20145215《网络对抗》Exp5 MSF基础应用

    20145215<网络对抗>Exp5 MSF基础应用 基础问题回答 用自己的话解释什么是exploit,payload,encode? exploit就相当于是载具,将真正要负责攻击的代码 ...

  6. sizeof 与 字节对齐

    转:http://baike.baidu.com/view/1356720.htm sizeof是运算符,可用于任何变量名.类型名或常量值,当用于变量名(不是数组名)或常量时,它不需要用圆括号.    ...

  7. C# 多窗体之间方法调用

    看似一个简单的功能需求,其实很多初学者处理不好的,很多朋友会这么写: //父窗体是是frmParent,子窗体是frmChildA //在父窗体中打开子窗体 frmChildA child = new ...

  8. org.apache.catalina.LifecycleException: Failed to stop component(生命周期异常)

    真是郁闷透顶,以前昨天还可以用,换了myeclipse自带的tomcat就可以用: 异常: org.apache.catalina.LifecycleException: Failed to stop ...

  9. java连接数据库读取数据出现乱码

    因为这是通用编码,像中国通常使用的GBK.GB2312.Big5等只是针对中文而言,但是对其他文字就不适用了,为了使得这个问题的解决具有文字编码通用性,所以我这里设定了UTF8这个编码. 编码一致性涉 ...

  10. eclipse如何加入第三方jar包

    1.项目右键选择“properties” 2.选Java Build Path 3.选Libraries 4.选add JRAS jar包下载平台:http://www.mvnrepository.c ...