转载自 :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. [SHOI2013]发牌 解题报告

    [SHOI2013]发牌 题意 对一个\(1\sim n(n\le 7\times 10^5)\)的环,指标最开始在\(1\),每次删去顺时针往后第\(d_i\)个元素,指标移到下一个位置.要求输出每 ...

  2. centos6.5下修改文件夹权限和用户名用户组

    0.说明 Linux系统下经常遇到文件或者文件夹的权限问题,或者是因为文件夹所属的用户问题而没有访问的权限.根据我自己遇到的情况,对这类问题做一个小结. 在命令行使用命令"ll"或 ...

  3. Libre 6013 「网络流 24 题」负载平衡 (网络流,最小费用最大流)

    Libre 6013 「网络流 24 题」负载平衡 (网络流,最小费用最大流) Description G 公司有n 个沿铁路运输线环形排列的仓库,每个仓库存储的货物数量不等.如何用最少搬运量可以使n ...

  4. (转)git中关于fetch的使用

    将远程仓库的分支及分支最新版本代码拉取到本地: 命令:git fetch 该命令执行后,不会将拉取的分支的最新代码合并到当前分支,仅仅是拉取/下载下来到本地仓库中. 首先,我们使用git branch ...

  5. GBDT原理详解

    从提升树出发,——>回归提升树.二元分类.多元分类三个GBDT常见算法. 提升树 梯度提升树 回归提升树 二元分类 多元分类 面经 提升树 在说GBDT之前,先说说提升树(boosting tr ...

  6. Codeforces Round #510 (Div. 2)(C)

    传送门:Problem C https://www.cnblogs.com/violet-acmer/p/9682082.html 题意: 给你n个数,定义有两种操作 ① 1 i j : (i != ...

  7. 20145215《网络对抗》Exp6 信息搜集与漏洞扫描

    20145215<网络对抗>Exp6 信息搜集与漏洞扫描 基础问题回答 哪些组织负责DNS,IP的管理? 全球根服务器均由美国政府授权的ICANN统一管理,负责全球的域名根服务器.DNS和 ...

  8. Java中Jdom解析XML

    JDOM与DOM类似,也是一组用于解析XML的API,它本身不是一个解析器,默认的它内置了Apache的Xerces解析器:JDOM与DOM不同的是,DOM是跨语言的一套API,Java世界中有很多D ...

  9. 多目标遗传算法 ------ NSGA-II (部分源码解析)两个个体支配判断 dominance.c

    /* Domination checking routines */ # include <stdio.h> # include <stdlib.h> # include &l ...

  10. java虚拟内存设置 防止内存溢出 OutOfMemory【转】【原】

    outofmemory permgen 这个问题主要还是由 java.lang.OutOfMemoryError: Java heap space 引起的. 有这两种解决方法: 1.设置环境变量 解决 ...