renran421 发表于 2018-6-13 09:32:12

python: 监控windows 下进程

  目的:
针对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文件,修改服务启动的路径和进程在任务管理器中的名字.




[*]
[*]ProgramPath: C:\Program Files\RhinoSoft.com\Serv-U\Serv-U.exe
[*]
[*]
[*]ProcessName: Serv-U.exe
[*]
[*]如:
[*]
[*]ProgramPath: C:\Program Files\Tencent\QQ\Bin\QQ.exe
[*]
[*]
[*]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
[*]    ifnot 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]
查看完整版本: python: 监控windows 下进程