代码讲解Python对Windows服务进行监控


Posted in Python onFebruary 11, 2018

我们首先来看下python的全部代码,大家可以直接复制后测试:

#-*- encoding: utf-8 -*-  
import logging  
import wmi  
import os  
import time  
from ConfigParser import ConfigParser  
import smtplib  
from email.mime.text import MIMEText  
import socket 
from datetime import datetime 
import re 
import sys 
import time 
import string 
import psutil  
import threading 
from threading import Timer   
import logging 
# 创建一个logger  
logger = logging.getLogger('Monitor')  
logger.setLevel(logging.DEBUG)  
   
# 创建一个handler,用于写入日志文件  
fh = logging.FileHandler('test.log')  
fh.setLevel(logging.DEBUG)  
   
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')  
fh.setFormatter(formatter)  
logger.addHandler(fh)  

reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入  
sys.setdefaultencoding('utf-8')  
 
def send_mail(to_list,sub,content):  
  CONFIGFILE = 'config.ini'  
  config = ConfigParser()  
  config.read(CONFIGFILE)  
  mail_host=config.get('Mail','mail_host')      #使用的邮箱的smtp服务器地址,这里是163的smtp地址  
  mail_user=config.get('Mail','mail_user')              #用户名  
  mail_pass=config.get('Mail','mail_pass')                #密码  
  mail_postfix=config.get('Mail','mail_postfix')           #邮箱的后缀,网易就是163.com  
  me=sub+"<"+mail_user+"@"+mail_postfix+">"  
  msg = MIMEText(content,_subtype='plain',_charset='utf-8')  
  msg['Subject'] = sub  
  msg['From'] = me  
  msg['To'] = ";".join(to_list)        #将收件人列表以‘;'分隔  
  try:  
    server = smtplib.SMTP()  
    server.connect(mail_host)              #连接服务器  
    server.login(mail_user,mail_pass)        #登录操作  
    server.sendmail(me, to_list, msg.as_string())  
    server.close()  
    return True  
  except Exception, e:  
    print str(e) 
    logger.info(str(e))    
    return False  
 
 
 #读取配置文件中的进程名和系统路径,这2个参数都可以在配置文件中修改 
ProList = []  
#定义一个列表 
c = wmi.WMI()  
 
#获取进程所用内存 
def countProcessMemoey(processName): 
  try: 
    CONFIGFILE = 'config.ini'  
    config = ConfigParser()  
    config.read(CONFIGFILE)  
 
    pattern = re.compile(r'([^\s]+)\s+(\d+)\s.*\s([^\s]+\sK)') 
    cmd = 'tasklist /fi "imagename eq ' + processName + '"' + ' | findstr.exe ' + processName 
    result = os.popen(cmd).read() 
    resultList = result.split("\n") 
    totalMem = 0.0 
    totalCpu = 0.0 
 
    print "*" * 80 
    for srcLine in resultList: 
      srcLine = "".join(srcLine.split('\n')) 
      if len(srcLine) == 0: 
        break 
      m = pattern.search(srcLine) 
      if m == None: 
        continue 
      #由于是查看python进程所占内存,因此通过pid将本程序过滤掉 
      if str(os.getpid()) == m.group(2): 
        continue 
      p = psutil.Process(int(m.group(2))) 
      cpu = p.cpu_percent(interval=1)   
      ori_mem = m.group(3).replace(',','') 
      ori_mem = ori_mem.replace(' K','') 
      ori_mem = ori_mem.replace(r'\sK','') 
      memEach = string.atoi(ori_mem) 
      totalMem += (memEach * 1.0 /1024) 
      totalCpu += cpu 
      print 'ProcessName:'+ m.group(1) + '\tPID:' + m.group(2) + '\tmemory size:%.2f'% (memEach * 1.0 /1024), 'M' + ' CPU:'+str(cpu)+'%' 
    print 'ProcessName:'+ m.group(1)+' TotalMemory:'+str(totalMem)+'M'+' totalCPU:'+str(totalCpu)+'%' 
    logger.info('ProcessName:'+ m.group(1)+' TotalMemory:'+str(totalMem)+'M'+' totalCPU:'+str(totalCpu)+'%') 
    print "*" * 80 
      
    if totalMem> float(config.get('MonitorProcessValue','Memory')): 
      print 'Memory Exceed!' 
      IP = socket.gethostbyname(socket.gethostname()) 
      now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') 
      subject = IP +' ' + processName + '内存使用量过高!' 
      content = now + ' ' + IP +' ' + processName + '内存使用量过高,达到'+str(totalMem) +'M\n请尽快处理!' 
      logger.info(processName +'内存使用量过高,达到'+str(totalMem) +'M') 
      send_mail(['sunwei_work@163.com','sunweiworkplace@gmail.com'],subject, content) 
    if totalCpu > float(config.get('MonitorProcessValue','CPU')): 
      print 'CPU Exceed!' 
      IP = socket.gethostbyname(socket.gethostname()) 
      now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') 
      subject = IP +' ' + processName + 'CPU使用率过高!' 
      content = now + ' ' + IP +' ' + processName + 'CPU使用率过高,达到'+str(totalCpu)+'%\n请尽快处理!' 
      logger.info(processName +'CPU使用率过高,达到'+str(totalMem) +'M') 
      send_mail(['sunwei_work@163.com','sunweiworkplace@gmail.com'],subject, content) 
  except Exception, e:  
    print str(e) 
    logger.info(str(e))   
  
#判断进程是否存活 
def judgeIfAlive(ProgramPath,ProcessName): 
  try: 
    print datetime.now().strftime('%Y-%m-%d %H:%M:%S') 
    for process in c.Win32_Process():  
      ProList.append(str(process.Name))  
    #把所有任务管理器中的进程名添加到列表 
 
    if ProcessName in ProList: 
      countProcessMemoey(ProcessName)  
    #判断进程名是否在列表中,如果是True,则所监控的服务正在 运行状态, 
    #打印服务正常运行 
      print ''  
      print ProcessName+" Server is running..."  
      print ''  
      logger.info(ProcessName+" Server is running...") 
    else:  
      #如果进程名不在列表中,即监控的服务挂了,则在log文件下记录日志 
      #日志文件名是以年月日为文件名 
      IP = socket.gethostbyname(socket.gethostname()) 
      now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') 
      subject = IP +' ' + ProcessName + '已停止运行!' 
      logger.info( ProcessName + '已停止运行!') 
      content = now + ' ' + IP +' ' + ProcessName + '已停止运行!' +'\n请尽快处理!' 
      send_mail(['sunwei_work@163.com','sunweiworkplace@gmail.com'],subject, content) 
      print ProcessName+' Server is not running...'  
      #打印服务状态 
      logger.info('\n'+'Server is not running,Begining to Restart Server...'+'\n'+(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()) +'\n')) 
      #写入时间和服务状态到日志文件中 
      os.startfile(ProgramPath)  
      #调用服务重启 
      logger.info(ProcessName+'Restart Server Success...'+'\n'+time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime())) 
      print ProcessName+'Restart Server Success...'  
      print time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime())  
    del ProList[:]  
    #清空列表,否则列表会不停的添加进程名,会占用系统资源 
  except Exception, e:  
    print str(e) 
    logger.info(str(e))   
def startMonitor(ProgramPathDict,ProcessNameDict) :  
  for i in range(0,len(ProcessNameDict)): 
    judgeIfAlive(ProgramPathDict[i],ProcessNameDict[i]) 
if __name__=="__main__" :  
  CONFIGFILE = 'config.ini'  
  config = ConfigParser()  
  config.read(CONFIGFILE)  
  ProgramPathDict = config.get('MonitorProgramPath','ProgramPath').split("|")  
  ProcessNameDict = config.get('MonitorProcessName','ProcessName').split("|") 
  while True:  
    startMonitor(ProgramPathDict,ProcessNameDict)  
    time.sleep(int(config.get('MonitorProcessValue','Time')))

所用配置文件config.ini

[MonitorProgramPath]  
ProgramPath: C:\Windows\System32\services.exe|C:\Program Files (x86)\Google\Chrome\Application\chrome.exe  
[MonitorProcessName]  
ProcessName: services.exe|chrome.exe 
[MonitorProcessValue] 
Memory:5000.0 
CPU:50.0 
Time:60 
[Mail]  
mail_host: smtp.163.com 
mail_user:  
mail_pass:  
mail_postfix: 163.com

以上就是本次小编整理的关于Python对Windows服务进行监控的全部代码内容,感谢你对三水点靠木的支持。

Python 相关文章推荐
Python 文件操作实现代码
Oct 07 Python
python 将字符串转换成字典dict
Mar 24 Python
Python正则表达式的使用范例详解
Aug 08 Python
在Python中操作日期和时间之gmtime()方法的使用
May 22 Python
Python数据库的连接实现方法与注意事项
Feb 27 Python
Python实现解析Bit Torrent种子文件内容的方法
Aug 29 Python
python奇偶行分开存储实现代码
Mar 19 Python
python看某个模块的版本方法
Oct 16 Python
python sklearn库实现简单逻辑回归的实例代码
Jul 01 Python
Win10+GPU版Pytorch1.1安装的安装步骤
Sep 27 Python
关于Python中定制类的比较运算实例
Dec 19 Python
Pytest mark使用实例及原理解析
Feb 22 Python
django 按时间范围查询数据库实例代码
Feb 11 #Python
python实现媒体播放器功能
Feb 11 #Python
python使用pycharm环境调用opencv库
Feb 11 #Python
Python元组及文件核心对象类型详解
Feb 11 #Python
详解Python核心对象类型字符串
Feb 11 #Python
python使用json序列化datetime类型实例解析
Feb 11 #Python
Python中pow()和math.pow()函数用法示例
Feb 11 #Python
You might like
Windows下的PHP5.0详解
2006/11/18 PHP
php获取textarea的值并处理回车换行的方法
2014/10/20 PHP
PHP数组实例详解
2016/06/26 PHP
PHP实现生成带背景的图形验证码功能
2016/10/03 PHP
javascript 二维数组的实现与应用
2010/03/16 Javascript
JavaScipt中的Math.ceil() 、Math.floor() 、Math.round() 三个函数的理解
2010/04/29 Javascript
基于jQuery的淡入淡出可自动切换的幻灯插件
2010/08/24 Javascript
jquery $.ajax()取xml数据的小问题解决方法
2010/11/20 Javascript
JS关闭窗口或JS关闭页面的几种代码分享
2013/10/25 Javascript
9款2014最热门jQuery实用特效推荐
2014/12/07 Javascript
JavaScript取得WEB安全颜色列表的方法
2015/07/14 Javascript
javascript函数式编程程序员的工具集
2015/10/11 Javascript
jQuery实现div横向拖拽排序的简单实例
2016/07/13 Javascript
初探JavaScript 面向对象(推荐)
2017/09/03 Javascript
Vue之Vue.set动态新增对象属性方法
2018/02/23 Javascript
Vue 父子组件数据传递的四种方式( inheritAttrs + $attrs + $listeners)
2018/05/04 Javascript
ES6 中可以提升幸福度的小功能
2018/08/06 Javascript
微信开发之微信jssdk录音功能开发示例
2018/10/22 Javascript
vue实现父子组件之间的通信以及兄弟组件的通信功能示例
2019/01/29 Javascript
ES6中字符串的使用方法扩展
2019/06/04 Javascript
node.js 使用 net 模块模拟 websocket 握手进行数据传递操作示例
2020/02/11 Javascript
关于AngularJS中几种Providers的区别总结
2020/05/17 Javascript
jQuery中event.target和this的区别详解
2020/08/13 jQuery
python检测某个变量是否有定义的方法
2015/05/20 Python
Python实现将SQLite中的数据直接输出为CVS的方法示例
2017/07/13 Python
Python实现搜索算法的实例代码
2020/01/02 Python
解决pycharm下pyuic工具使用的问题
2020/04/08 Python
使用keras2.0 将Merge层改为函数式
2020/05/23 Python
python实现测试工具(二)——简单的ui测试工具
2020/10/19 Python
美国创意之家:BulbHead
2017/07/12 全球购物
马来西亚最大的在线隐形眼镜商店:MrLens
2019/03/27 全球购物
大学生求职信范文应怎么写
2014/01/01 职场文书
酒店中秋节活动方案
2014/01/31 职场文书
优秀教师主要事迹
2014/02/01 职场文书
2014年党员承诺书范文
2014/05/20 职场文书
2015社区六五普法工作总结
2015/04/21 职场文书