设为首页 收藏本站
查看: 802|回复: 0

[经验分享] python: 监控windows 下进程

[复制链接]

尚未签到

发表于 2018-6-13 09:32:12 | 显示全部楼层 |阅读模式
  目的:
针对Windows下进程异常退出后,此程序自动启动被监控进程。如:监控Serv-U.exe
程序是使用python语言编写,可在Windows下双击MonitorWin32Process.exe直接运行。程序会按照config.ini配置文件,进行监控进程。如果没有被监控的进程,则会按照进程启动路径自动启动。
详细使用请查看压包内的使用说明.
  1.. 环境配置
2.. 使用说明
3.. 待改进
4.. 下载链接
  5.. 发邮件通知功能源码.
1.. 环境配置
  需要的安装包python、wmi
介绍wmi 网站


  • http://tgolden.sc.sabren.com/python/wmi/index.html#what-is-it

  xp 安装WMI


  • Windows installer: http://timgolden.me.uk/python/downloads/WMI-1.4.6.win32.exe

  win7 将安装包解压到python lib 目录下,详细查看readme文件。


  • Zipped-up source: http://timgolden.me.uk/python/downloads/WMI-1.4.6.zip

环境配置可能遇到的问题


  • C:\Python27\Lib\WMI-1.4.6>python setup.py install
  • Traceback (most recent call last):
  •   File &quot;setup.py&quot;, line 2, in <module>
  •     import wmi
  •   File &quot;C:\Python27\Lib\WMI-1.4.6\wmi.py&quot;, line 88, in <module>
  •     from win32com.client import GetObject, Dispatch
  •     ImportError: No module named win32com.client

解决方法:

相应python版本的win32扩展,安装后问题即解决。网址如下:

http://sourceforge.net/projects/pywin32/files/
  程序代码


  • #!-*- encoding: utf-8 -*-
  • import logging
  • import wmi
  • import os
  • import time
  • from ConfigParser import ConfigParser

  • CONFIGFILE='./config.ini'
  • config = ConfigParser()
  • config.read(CONFIGFILE)

  • ProgramPath = config.get('MonitorProgramPath','ProgramPath')
  • ProcessName = config.get('MonitorProcessName','ProcessName')


  • c = wmi.WMI()

  • def main():
  •   
  •    ProList = []             #如果在main()函数之外ProList 不会清空列表内容.
  •     for process in c.Win32_Process():
  •         ProList.append(str(process.Name))

  •     if ProcessName in ProList:
  •         print &quot;Service &quot; + ProcessName + &quot; is running...!!!&quot;
  •         if os.path.isdir(&quot;c:\MonitorWin32Process&quot;):
  •             pass
  •         else:
  •             os.makedirs(&quot;c:\MonitorWin32Process&quot;)

  •     else:
  •         print &quot;Service &quot; + ProcessName + &quot; error ...!!!&quot;
  •         os.startfile(ProgramPath)

  • if __name__ == &quot;__main__&quot;:
  •     while True:
  •         main()
  •         time.sleep(300)



1..2 将py程序编译成windows下可执行文件

py2exe下载地址,找到与安装的Python 版本相同的py2exe版本.


  • http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/

  • from distutils.core import setup
  • import py2exe

  • setup(console=['MonitorWin32Process.py'],   
  • )

问题描述:
当执行C:\Documents and Settings\Administrator\Desktop\temp>python setup.py py2exe
执行一段代码后出现 弹出一个窗口提示Python.exe 程序将要结束的
解决方法 :
这是因为setup.py中 logo.ico图片是由原来的gif 直接修改后缀名为ico 造成的.


  • from distutils.core import setup
  • import py2exe
  •   
  • setup(
  • console = [{&quot;script&quot; : &quot;MonitorWin32Process.py&quot;, &quot;icon_resources&quot; : [(1, &quot;logo.ico&quot;)]}]
  • )

  注: 将以上 console 修改windowns 在windowns下的可执行程序,将不会出现cmd窗口.
  
2.. 使用说明
2..1 必须先配置config.ini
配置压缩包中config.ini文件,修改服务启动的路径和进程在任务管理器中的名字.




  • [MonitorProgramPath]
  • ProgramPath: C:\Program Files\RhinoSoft.com\Serv-U\Serv-U.exe
  •   
  • [MonitorProcessName]
  • ProcessName: Serv-U.exe
  •   
  • 如:
  • [MonitorProgramPath]
  • ProgramPath: C:\Program Files\Tencent\QQ\Bin\QQ.exe
  •   
  • [MonitorProcessName]
  • ProcessName: QQ.exe

2..2
将MonitorWin32Process.exe拖到启动中. 即可开机启动.
3.. 待改进

3..1 出现错误时在屏幕上一闪马上消失了.

应添加下面红色代码,这样有利于排查错误.



  • if ProcessName in ProList:
  •     print &quot;Service &quot; + ProcessName + &quot; is running...!!!&quot;
  •     if os.path.isdir(&quot;c:\MonitorWin32Process&quot;):
  •         pass
  •     else:
  •         os.makedirs(&quot;c:\MonitorWin32Process&quot;)

  • else:
  •     print &quot;Service &quot; + ProcessName + &quot; error ...!!!&quot;
  •     os.startfile(ProgramPath)
  •     time.sleep(5)

  3..2 应该加上日志功能.
  按天或按月进行分日志.
  4.. 下载链接


  • http://down.51cto.com/data/381581

  5. 发邮件通知功能源码.


  • #!-*- encoding: utf-8 -*-
  • import wmi,os,time,smtplib
  • from ConfigParser import ConfigParser
  • from email.mime.text import MIMEText

  • #### 发送邮件 代码开始

  • #####################
  • #获取smtp服务器,用户名、口令、邮箱的后缀、收件人列表
  • CONFIGFILE=&quot;./config.ini&quot;
  • config = ConfigParser()
  • config.read(CONFIGFILE)

  • mailHost = config.get('mailHost','Host')
  • mailUser = config.get('mailUser','User')
  • mailPass = config.get('mailPass','Pass')
  • mailPostfix = config.get('mailPostfix','Postfix')
  • mailToList = config.get('mailToList','toList')

  • #获取主题
  • subject = config.get('subject','subject')


  • ######################

  • def send_mail(mailToList,sub,content):
  •     '''
  •     to_list:发给谁
  •     sub:主题
  •     content:内容
  •     '''
  •     RealTime = time.strftime(&quot;%Y-%m-%d %X&quot;,time.localtime())
  •     content = RealTime + &quot; &quot; + content
  •     me=&quot;Monitor&quot;+&quot;<&quot;+mailUser+&quot;@&quot;+mailPostfix+&quot;>&quot;
  •     msg = MIMEText(content,'plain','gb2312')
  •     msg['Subject'] = sub
  •     msg['From'] = me
  •     msg['To'] = mailToList
  •     try:
  •         s = smtplib.SMTP()
  •         s.connect(mailHost)
  •         s.login(mailUser,mailPass)
  •         s.sendmail(me, mailToList, msg.as_string())
  •         s.close()
  •         return True
  •     except Exception, e:
  •         print str(e)
  •         return False
  • #### 发送邮件 代码结束

  • dirName = &quot;d:\MonitorWin32Process\\&quot;
  • logSuffix = &quot;.log&quot;
  • logErrorSuffix = &quot;.error.log&quot;
  • config = ConfigParser()
  • config.read(CONFIGFILE)

  • ProgramPath = config.get('MonitorProgramPath','ProgramPath')
  • ProcessName = config.get('MonitorProcessName','ProcessName')  
  • SleepTime = config.get('ProcessSleepTime','SleepTime')

  • if not os.path.isdir(dirName):
  •     os.makedirs(dirName)

  • c = wmi.WMI()

  • def main():  
  •     ProList = []               #如果在main()函数之外ProList 不会清空列表内容.
  •     timetimeDay = time.strftime(&quot;%Y-%m-%d&quot;,time.localtime())
  •     timetimeLog = time.strftime(&quot;%Y-%m-%d %X&quot;,time.localtime())
  •     logFileName = dirName + timeDay + logSuffix
  •     logFileNameError = dirName + timeDay + logErrorSuffix
  •     if  not os.path.isfile(logFileName):
  •         file(logFileName,'a')

  •     for process in c.Win32_Process():  
  •         ProList.append(str(process.Name))  

  •     if ProcessName in ProList:  
  •         content = timeLog + &quot; Service &quot; + ProcessName + &quot; is running...!!!\n&quot;  
  •         logFile = open(logFileName,'a+')
  •         logFile.write(content)
  •         logFile.close()

  •     else:
  •         content = timeLog + &quot; Service &quot; + ProcessName + &quot; is error !!!&quot; + &quot;\n&quot;
  •         logFile = open(logFileNameError,'a+')
  •         logFile.write(content)
  •         logFile.close()
  •         os.startfile(ProgramPath)
  •         send_mail(mailToList,subject,content)
  •          

  • if __name__ == &quot;__main__&quot;:
  •     while True:
  •         main()
  •         time.sleep(int(SleepTime))

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-523083-1-1.html 上篇帖子: Windows下MySQL多实例运行 下篇帖子: windows下强制杀死tomcat进程
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表