使用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)
相关文章
|
11天前
|
Python
用python转移小文件到指定目录并压缩,脚本封装
这篇文章介绍了如何使用Python脚本将大量小文件转移到指定目录,并在达到大约250MB时进行压缩。
25 2
|
16天前
|
运维 Prometheus 监控
自动化运维的魔法:使用Python脚本简化日常任务
【8月更文挑战第50天】在数字化时代的浪潮中,自动化运维成为提升效率、减少人为错误的利器。本文将通过一个实际案例,展示如何利用Python脚本实现自动化部署和监控,从而让运维工作变得更加轻松和高效。我们将一起探索代码的力量,解锁自动化运维的神秘面纱,让你的工作环境焕然一新。
129 81
|
2天前
|
安全 Python
Python脚本实现IP按段分类
【10月更文挑战第04天】
14 7
|
6天前
|
机器学习/深度学习 人工智能 运维
自动化运维的魔法:如何利用Python脚本提升工作效率
【9月更文挑战第29天】在数字时代的浪潮中,IT运维人员面临着前所未有的挑战和机遇。本文将通过深入浅出的方式,介绍自动化运维的基本概念、核心价值以及使用Python脚本实现自动化任务的方法。我们将从实际案例出发,探讨如何利用Python简化日常的系统管理任务,提高运维效率,并展望自动化运维的未来趋势。无论你是初学者还是有经验的运维专家,这篇文章都将为你开启一扇通往高效工作方式的大门。
10 2
|
8天前
|
监控
MASM32写的免费软件“ProcView/系统进程监控” V1.4.4003 说明和下载
MASM32写的免费软件“ProcView/系统进程监控” V1.4.4003 说明和下载
|
9天前
|
Web App开发 存储 安全
Python编写脚本,打开浏览器输入网址,自动化登陆网站
Python编写脚本,打开浏览器输入网址,自动化登陆网站
15 4
|
12天前
|
运维 监控 Python
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第23天】在本文中,我们将探索如何通过编写Python脚本来自动化常见的系统管理任务,从而提升效率并减少人为错误。文章将介绍基础的Python编程概念、实用的库函数,以及如何将这些知识应用于创建有用的自动化工具。无论你是新手还是有经验的系统管理员,这篇文章都将为你提供有价值的见解和技巧,帮助你在日常工作中实现自动化。
|
14天前
|
运维 监控 安全
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第21天】在快速迭代的软件开发环境中,运维工作往往因为重复性高、易出错而被诟病。本文将介绍如何通过编写简单的Python脚本来自动化这些日常任务,从而提升效率和减少错误。我们将以实际案例为基础,展示如何从零开始构建一个自动化脚本,并解释其背后的原理。文章旨在启发读者思考如何利用编程技能来解决工作中的实际问题,进而探索技术与日常工作流程结合的可能性。
|
9天前
|
Python Windows
python之windows脚本启动bat
python之windows脚本启动bat
|
11天前
|
负载均衡 Java 调度
探索Python的并发编程:线程与进程的比较与应用
本文旨在深入探讨Python中的并发编程,重点比较线程与进程的异同、适用场景及实现方法。通过分析GIL对线程并发的影响,以及进程间通信的成本,我们将揭示何时选择线程或进程更为合理。同时,文章将提供实用的代码示例,帮助读者更好地理解并运用这些概念,以提升多任务处理的效率和性能。
下一篇
无影云桌面