最近比较烦,研发给的pc服务版本在虚拟机上已经开始给客户使用了,服务老是莫名的死翘翘,客户不停的电话给我,搞的我心情很差,于是在一个下午,静下心来,用python写了个简单的监控进程的脚本,当发现进程消失的时候,立即调用服务,开启服务。。。

   脚本的工作原理是这样的:脚本读取配置文件,读取预先配置好的调用系统服务的路径和所要监控的服务在进程管理器中的进程名,之所以要用配置文件,是为了方便给需要的朋友,你只需要修改进程名和系统路径,源代码就不需要修改了。具体的看代码中的注释吧。。。下面的是配置文件 config.ini

 
  

  1. [MonitorProgramPath] 
  2. ProgramPath: C:\Program Files\SSH Communications Security\SSH Secure Shell\SshClient.exe 
  3.  
  4. [MonitorProcessName] 
  5. ProcessName: SshClient.exe 

上面可以根据你的需求配置不同的路径和进程名,我是需要监控SshClient.exe 这个程序,那就配置好他的调用的系统路径和他在任务管理器里面的进程名。

下面来看看代码:

 

 
  
  1. #-*- encoding: utf-8 -*- 
  2. import logging 
  3. import wmi 
  4. import os 
  5. import time 
  6. from ConfigParser import ConfigParser 
  7. CONFIGFILE = 'config.ini' 
  8. config = ConfigParser() 
  9. config.read(CONFIGFILE) 
  10. ProgramPath = config.get('MonitorProgramPath','ProgramPath'
  11. ProcessName = config.get('MonitorProcessName','ProcessName'
  12. #读取配置文件中的进程名和系统路径,这2个参数都可以在配置文件中修改
  13. ProList = [] 
  14. #定义一个列表
  15. c = wmi.WMI() 
  16.  
  17. def main(): 
  18.     for process in c.Win32_Process(): 
  19.         ProList.append(str(process.Name)) 
  20. #把所有任务管理器中的进程名添加到列表
  21.  
  22.     if ProcessName in ProList: 
  23. #判断进程名是否在列表中,如果是True,则所监控的服务正在 运行状态,
  24. #打印服务正常运行
  25.         print '' 
  26.         print "Server is running..." 
  27.         print '' 
  28.     else
  29. #如果进程名不在列表中,即监控的服务挂了,则在log文件下记录日志
  30. #日志文件名是以年月日为文件名
  31.  
  32.         f=open('.\\log\\'+time.strftime("%Y%m%d", time.localtime())+'-exception.txt','a') 
  33.         print 'Server is not running,Begining to Restart Server...' 
  34. #打印服务状态
  35.         f.write('\n'+'Server is not running,Begining to Restart Server...'+'\n'
  36.         f.write(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()) +'\n')
  37.  #写入时间和服务状态到日志文件中
  38.         os.startfile(ProgramPath) 
  39. #调用服务重启
  40.         f.write('Restart Server Success...'+'\n'
  41.         f.write(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime())) 
  42.         f.close() 
  43. #关闭文件
  44.         print 'Restart Server Success...' 
  45.         print time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()) 
  46.     del ProList[:] 
  47. #清空列表,否则列表会不停的添加进程名,会占用系统资源
  48.      
  49. if __name__=="__main__" : 
  50.     while True
  51.         main() 
  52.         time.sleep(10
  53. #每隔10秒调用脚本看下服务是否正常,如果不正常则重启服务,如果正常,则打印服务正常
  54.          

   呵呵,脚本还是很简单的,需要的朋友可以拿去玩玩,只要修改配置文件就可以了,不需要修改源代码,就能拿去跑跑,希望对大家的工作和学习有帮助,如果在使用中有问题,可以给我建议。。。