python监控进程脚本


Posted in Python onApril 12, 2018

本文实例为大家分享了python监控进程脚本的具体代码,供大家参考,具体内容如下

原理:

监控一个指定进程,每隔5秒钟获取其CPU、内存使用量超过60%即kill掉该进程,获取其句柄数,超过300也kill掉该进程

运行环境是windows 64位系统+python 2.7 64位 ,这里需要使用到psutil 类库,要另外安装。脚本里面可以自动安装,前提是你已经下载好了安装包psutil-3.3.0.win-amd64-py2.7.exe

下面看代码:

#!/usr/bin/env python 
# -*- coding:utf-8 -*- 
 
 
import time 
from datetime import date, datetime, timedelta 
import platform 
import os 
import win32ui,win32api,win32con,win32gui 
import subprocess 
 
 
def install(): 
 print("install psutil...") 
 sysstr = platform.system() 
 if(sysstr =="Windows"): 
  print ("Call Windows tasks") 
  bit,type=platform.architecture() 
  print ("os bit: %s " % bit) 
  #print ("os type: %s " % type) 
  if(bit == "64bit"): 
   fileName="psutil-3.3.0.win-amd64-py2.7.exe"; 
  else: 
   fileName="psutil-3.3.0.win32-py2.7.exe"; 
  print("will install the file [%s]" % fileName) 
   
  #启动程序--4种方法 
  #subprocess.Popen(fileName); #非阻塞 
  #subprocess.Popen(fileName).wati(); #阻塞   
  #os.system(fileName); #阻塞 
  #win32api.ShellExecute(0, 'open', fileName, '','',0) 
   
  label = 'Setup' #此处假设主窗口名为tt 
  hld = win32gui.FindWindow(None, label)   
  count=0 
  while (hld == 0 and count<20): 
   print("the setup is no running,will run it...") 
   count += 1 
   win32api.ShellExecute(0, 'open', fileName, '','',0)    
   print("sleep 1 seconds...") 
   time.sleep(0.5) 
   #wnd = win32ui.GetForegroundWindow() 
   #print wnd.GetWindowText() 
   hld = win32gui.FindWindow(None, label) 
   print("hld is %s" % hld) 
   
  pwin=win32ui.FindWindow(None,label)   
  print("pwin is %s" % pwin) 
  print pwin.GetWindowText() 
  print("click...") 
  button2=win32ui.FindWindowEx(pwin,None,None,'下一步(&N) >') #找到按钮 
  button2.SendMessage(win32con.BM_CLICK, 0,-1) 
  button2=win32ui.FindWindowEx(pwin,None,None,'下一步(&N) >') #找到按钮 
  button2.SendMessage(win32con.BM_CLICK, 0,-1) 
  button2=win32ui.FindWindowEx(pwin,None,None,'下一步(&N) >') #找到按钮 
  button2.SendMessage(win32con.BM_CLICK, 0,-1) 
  button2=win32ui.FindWindowEx(pwin,None,None,'完成') #找到按钮 
  button2.SendMessage(win32con.BM_CLICK, 0,-1) 
  print("install done...") 
 
 
  # 鼠标点击 
  #print("click...") 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) 
  #time.sleep(0.1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) 
  #time.sleep(1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) 
  #time.sleep(0.1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) 
  #time.sleep(1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) 
  #time.sleep(0.1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) 
  #time.sleep(1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) 
  #time.sleep(0.1) 
  #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) 
   
 elif(sysstr == "Linux"): 
  print ("Call Linux tasks") 
 else: 
  print ("Other System tasks") 
   
try: 
 print("import psutil...") 
 import psutil  
except Exception,e: 
 print Exception,":",e 
 install() 
 import psutil 
 
 
 
def get_proc_by_id(pid): 
 return psutil.Process(pid) 
 
 
def get_proc_by_name(pname): 
 """ get process by name 
  
 return the first process if there are more than one 
 """ 
 for proc in psutil.process_iter(): 
  try: 
<span style="white-space:pre">   </span># return if found one 
   if proc.name().lower() == pname.lower():<span style="white-space:pre">   </span> 
    return proc<span style="white-space:pre">    </span> 
  except psutil.AccessDenied: 
   pass 
  except psutil.NoSuchProcess: 
   pass 
 return None 
 
 
 
 
def getProcess(pname, day=0, hour=0, min=0, second=0):  
 # Init time 
 now = datetime.now() 
 strnow = now.strftime('%Y-%m-%d %H:%M:%S') 
 print "now:",strnow 
 # First next run time 
 period = timedelta(days=day, hours=hour, minutes=min, seconds=second) 
 next_time = now + period 
 strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S') 
 print "next run time:",strnext_time 
 while True: 
  # Get system current time 
  iter_now = datetime.now() 
  iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')  
  if str(iter_now_time) == str(strnext_time): 
   next_time = iter_now + period 
   strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S') 
   print "next run time:",strnext_time 
    
   try: 
    Process=get_proc_by_name(pname) 
   except Exception,e: 
    print Exception,":",e 
   if Process != None : 
    print "-------Found the process : %s" % Process.name(); 
    print("pid is (%s)" % Process.pid); 
    Cpu_usage = Process.cpu_percent(interval=1) 
    print("cpu percent is (%s)" % Cpu_usage); 
    if (100-Cpu_usage) < 0.1 : 
     print "cpu percent larger 60,now will terminate this process !"; 
     Process.terminate(); 
     Process.wait(timeout=3); 
     continue 
    RAM_percent = Process.memory_percent() 
    print("memory percent is (%s)" % RAM_percent); 
    if (60-RAM_percent) < 0.1 : 
     print "memory percent larger 60,now will terminate this process !"; 
     Process.terminate(); 
     Process.wait(timeout=3); 
     continue   
    all_files = list(Process.open_files()); 
    print("open files size is (%d)" % len(all_files)); 
    if (len(all_files)>300) : 
     print "open files size larger 300,now will terminate this process !"; 
     Process.terminate(); 
     Process.wait(timeout=3); 
     continue 
    Threads_Num=Process.num_threads() 
    print("threads number is (%s)" % Threads_Num); 
    if (Threads_Num>200) : 
     print "threads number larger 200,now will terminate this process !"; 
     Process.terminate(); 
     Process.wait(timeout=3); 
     continue 
   else : 
    print "-------No found the process : %s" % pname; 
    
   continue 
 
 
if __name__ == '__main__': 
 print("main....") 
 getProcess("QQ.exe",second=5)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
布同自制Python函数帮助查询小工具
Mar 13 Python
Python使用multiprocessing实现一个最简单的分布式作业调度系统
Mar 14 Python
Python实现遍历目录的方法【测试可用】
Mar 22 Python
python面向对象法实现图书管理系统
Apr 19 Python
selenium处理元素定位点击无效问题
Jun 12 Python
对python 树状嵌套结构的实现思路详解
Aug 09 Python
Python迭代器模块itertools使用原理解析
Dec 11 Python
python pymysql链接数据库查询结果转为Dataframe实例
Jun 05 Python
如何使用python自带IDLE的几种方法
Oct 10 Python
AI:如何训练机器学习的模型
Apr 16 Python
实例讲解Python中sys.argv[]的用法
Jun 03 Python
python中tkinter复选框使用操作
Nov 11 Python
使用Eclipse如何开发python脚本
Apr 11 #Python
一份python入门应该看的学习资料
Apr 11 #Python
Python实现时钟显示效果思路详解
Apr 11 #Python
pandas数据分组和聚合操作方法
Apr 11 #Python
使用pandas对矢量化数据进行替换处理的方法
Apr 11 #Python
pandas数据框,统计某列数据对应的个数方法
Apr 11 #Python
pandas按若干个列的组合条件筛选数据的方法
Apr 11 #Python
You might like
php提示Call-time pass-by-reference has been deprecated in的解决方法[已测]
2012/05/06 PHP
为PHP5.4开启Zend OPCode缓存
2014/12/26 PHP
php对文件夹进行相关操作(遍历、计算大小)
2015/11/04 PHP
Laravel + Elasticsearch 实现中文搜索的方法
2020/02/02 PHP
HTML上传控件取消选择
2013/03/06 Javascript
分享Javascript中最常用的55个经典小技巧
2013/11/29 Javascript
node.js中的fs.fstatSync方法使用说明
2014/12/15 Javascript
详解JavaScript逻辑And运算符
2015/12/04 Javascript
JavaScript、tab切换完整版(自动切换、鼠标移入停止、移开运行)
2016/01/05 Javascript
jQuery插件Flexslider实现图片轮播、图文结合滑动切换效果
2020/04/16 Javascript
jQuery中ScrollTo用法示例
2016/09/04 Javascript
微信小程序  http请求封装详解及实例代码
2017/02/15 Javascript
NodeJS爬虫实例之糗事百科
2017/12/14 NodeJs
使用npm安装最新版本nodejs
2018/01/18 NodeJs
vue组件中使用props传递数据的实例详解
2018/04/08 Javascript
关于Mac下安装nodejs、npm和cnpm的教程
2018/04/11 NodeJs
vue动画打包后失效问题的解决方法
2018/09/18 Javascript
Vue.js结合bootstrap前端实现分页和排序效果
2018/12/29 Javascript
nodejs分离html文件里面的js和css的方法
2019/04/09 NodeJs
Vue.js获取手机系统型号、版本、浏览器类型的示例代码
2020/05/10 Javascript
Vue微信公众号网页分享的示例代码
2020/05/28 Javascript
原生JavaScript写出Tabs标签页的实例代码
2020/07/20 Javascript
解决vue axios跨域 Request Method: OPTIONS问题(预检请求)
2020/08/14 Javascript
[46:57]EG vs Winstrike 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
Django基于ORM操作数据库的方法详解
2018/03/27 Python
python bluetooth蓝牙信息获取蓝牙设备类型的方法
2019/11/29 Python
Python如何实现FTP功能
2020/05/28 Python
浅析Python 条件控制语句
2020/07/15 Python
python matplotlib工具栏源码探析三之添加、删除自定义工具项的案例详解
2021/02/25 Python
CSS3等相关属性制作分页导航实现代码
2012/12/24 HTML / CSS
canvas离屏技术与放大镜实现代码示例
2018/08/31 HTML / CSS
Waterford美国官网:爱尔兰水晶制品品牌
2017/04/26 全球购物
2014年大学生就业规划书
2014/04/04 职场文书
房屋继承公证书
2014/04/10 职场文书
保护环境的标语
2014/06/09 职场文书
2015年民兵整组工作总结
2015/07/24 职场文书