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实现简单的服务器功能
Aug 25 Python
Python实现打印螺旋矩阵功能的方法
Nov 21 Python
Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法
Mar 13 Python
django 将model转换为字典的方法示例
Oct 16 Python
详解django+django-celery+celery的整合实战
Mar 19 Python
Django实现发送邮件功能
Jul 18 Python
用Python画一个LinkinPark的logo代码实例
Sep 10 Python
Python hashlib模块实例使用详解
Dec 24 Python
使用openCV去除文字中乱入的线条实例
Jun 02 Python
解决tensorflow读取本地MNITS_data失败的原因
Jun 22 Python
python获得命令行输入的参数的两种方式
Nov 02 Python
pycharm使用技巧之自动调整代码格式总结
Nov 04 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简单实现加减乘除计算器
2014/01/06 PHP
php使用curl检测网页是否被百度收录的示例分享
2014/01/31 PHP
php天翼开放平台短信发送接口实现方法
2014/12/22 PHP
PHP Imagick完美实现图片裁切、生成缩略图、添加水印
2016/02/22 PHP
PHP判断是否微信访问的方法示例
2019/03/27 PHP
dwr spring的集成实现代码
2009/03/22 Javascript
js中判断Object、Array、Function等引用类型对象是否相等
2012/08/29 Javascript
Javascript高级技巧分享
2014/02/25 Javascript
js动态拼接正则表达式的两种方法
2014/03/04 Javascript
JavaScript数据类型检测代码分享
2015/01/26 Javascript
JavaScript jquery及AJAX小结
2016/01/24 Javascript
js创建数组的简单方法
2016/07/27 Javascript
AngularJs $parse、$eval和$observe、$watch详解
2016/09/21 Javascript
Angular2使用Augury来调试Angular2程序
2017/05/21 Javascript
ES6正则表达式扩展笔记
2017/07/25 Javascript
快速掌握jquery分页插件jqPaginator的使用方法
2017/08/09 jQuery
微信小程序dom操作的替代思路实例分析
2018/12/06 Javascript
Angular中使用ng-zorro图标库部分图标不能正常显示问题
2019/04/22 Javascript
antd 表格列宽自适应方法以及错误处理操作
2020/10/27 Javascript
Python设计实现的计算器功能完整实例
2017/08/18 Python
Python3模拟curl发送post请求操作示例
2019/05/03 Python
Pandas0.25来了千万别错过这10大好用的新功能
2019/08/07 Python
ORM Django 终端打印 SQL 语句实现解析
2019/08/09 Python
Django中create和save方法的不同
2019/08/13 Python
pytorch 加载(.pth)格式的模型实例
2019/08/20 Python
使用python求解二次规划的问题
2020/02/29 Python
为什么相对PHP黑python的更少
2020/06/21 Python
使用CSS3 制作一个material-design 风格登录界面实例
2016/12/12 HTML / CSS
Mytheresa美国官网:德国知名的女性奢侈品电商
2017/05/27 全球购物
中职生自荐信
2013/10/13 职场文书
如何写毕业求职自荐信
2013/11/06 职场文书
项目合作意向书范本
2014/04/01 职场文书
《乌鸦喝水》教学反思
2016/02/19 职场文书
Linux安装Nginx步骤详解
2021/03/31 Servers
详细介绍MySQL中limit和offset的用法
2022/05/06 MySQL
Python爬取奶茶店数据分析哪家最好喝以及性价比
2022/09/23 Python