使用python脚本来监控进程

简介: 使用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:
        # return if found one
        if proc.name().lower() == pname.lower():
            return proc
        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)
相关文章
|
1月前
|
JSON 算法 API
深度分析小红书城API接口,用Python脚本实现
小红书作为以UGC内容为核心的生活方式平台,其非官方API主要通过移动端抓包解析获得,涵盖内容推荐、搜索、笔记详情、用户信息和互动操作等功能。本文分析了其接口体系、认证机制及请求规范,并提供基于Python的调用框架,涉及签名生成、登录态管理与数据解析。需注意非官方接口存在稳定性与合规风险,使用时应遵守平台协议及法律法规。
|
1月前
|
JSON API 数据安全/隐私保护
【干货满满】分享微店API接口到手价,用python脚本实现
微店作为知名社交电商平台,其开放平台提供商品查询、订单管理等API接口。本文介绍如何通过微店API获取商品到手价(含优惠、券等),涵盖认证机制、Python实现及关键说明。
|
1月前
|
JSON API 数据安全/隐私保护
【干货满满】分享淘宝API接口到手价,用python脚本实现
淘宝开放平台通过API可获取商品到手价,结合商品详情与联盟接口实现优惠计算。需使用AppKey、AppSecret及会话密钥认证,调用taobao.tbk.item.info.get接口获取最终价格。代码示例展示签名生成与数据解析流程。
|
1月前
|
JSON API 数据格式
深度分析大麦网API接口,用Python脚本实现
大麦网为国内领先演出票务平台,提供演唱会、话剧、体育赛事等票务服务。本文基于抓包分析其非官方接口,并提供Python调用方案,涵盖演出列表查询、详情获取及城市列表获取。需注意非官方接口存在稳定性风险,使用时应遵守平台规则,控制请求频率,防范封禁与法律风险。适用于个人学习、演出信息监控等场景。
|
1月前
|
JSON API 开发者
深度分析阿里妈妈API接口,用Python脚本实现
阿里妈妈是阿里巴巴旗下营销平台,提供淘宝联盟、直通车等服务,支持推广位管理、商品查询等API功能。本文详解其API调用方法,重点实现商品推广信息(佣金、优惠券)获取,并提供Python实现方案。
|
1月前
|
JSON API 数据安全/隐私保护
【干货满满】分享拼多多API接口到手价,用python脚本实现
拼多多开放平台提供商品价格查询API,通过“pdd.ddk.goods.detail”接口可获取商品基础价、优惠券、拼团价等信息。结合client_id、client_secret及签名机制实现身份认证,支持推广位ID获取专属优惠。本文提供完整Python实现,涵盖签名生成、接口调用与价格解析逻辑,适用于比价工具、导购平台等场景。
|
1月前
|
API 数据安全/隐私保护 开发者
深度分析苏宁API接口,用Python脚本实现
深度分析苏宁API接口,用Python脚本实现
|
1月前
|
JSON API 数据安全/隐私保护
深度分析虾皮城API接口,用Python脚本实现
虾皮开放平台提供丰富的API接口,支持商品管理、订单处理及促销信息查询等功能。本文详解API认证机制与调用方法,基于Python实现商品价格及到手价获取方案,适用于电商数据分析与运营。
|
1月前
|
前端开发 Shell API
深度分析58同城API接口,用Python脚本实现
58同城为国内知名分类信息平台,涵盖房产、招聘、二手车等多领域。本文基于网页抓包与解析,分享其非官方接口的Python实现方案,分析核心接口特性与反爬应对策略,适用于数据学习与信息聚合。注意:非官方接口存在风险,使用需遵守平台规则。
|
1月前
|
JSON API 数据安全/隐私保护
【干货满满】分享京东API接口到手价,用python脚本实现
淘宝开放平台提供丰富API,通过商品详情接口与淘宝联盟接口,可获取含优惠券、满减后的商品到手价。本文介绍基于Python的实现方案,涵盖签名生成、接口调用、价格解析及错误处理,适用于比价工具、导购平台等场景。

推荐镜像

更多