使用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)
相关文章
|
2月前
|
Python
自动化微信朋友圈:Python脚本实现自动发布动态
本文介绍如何使用Python脚本自动化发布微信朋友圈动态,节省手动输入的时间。主要依赖`pyautogui`、`time`、`pyperclip`等库,通过模拟鼠标和键盘操作实现自动发布。代码涵盖打开微信、定位朋友圈、准备输入框、模拟打字等功能。虽然该方法能提高效率,但需注意可能违反微信使用条款,存在风险。定期更新脚本以适应微信界面变化也很重要。
200 61
|
23天前
|
安全 Linux 网络安全
利用Python脚本自动备份网络设备配置
通过本文的介绍,我们了解了如何利用Python脚本自动备份网络设备配置。该脚本使用 `paramiko`库通过SSH连接到设备,获取并保存配置文件。通过定时任务调度,可以实现定期自动备份,确保网络设备配置的安全和可用。希望这些内容能够帮助你在实际工作中实现网络设备的自动化备份。
48 14
|
2月前
|
数据采集 存储 监控
21个Python脚本自动执行日常任务(2)
21个Python脚本自动执行日常任务(2)
126 7
21个Python脚本自动执行日常任务(2)
|
2月前
|
数据挖掘 vr&ar C++
让UE自动运行Python脚本:实现与实例解析
本文介绍如何配置Unreal Engine(UE)以自动运行Python脚本,提高开发效率。通过安装Python、配置UE环境及使用第三方插件,实现Python与UE的集成。结合蓝图和C++示例,展示自动化任务处理、关卡生成及数据分析等应用场景。
172 5
|
2月前
|
Android开发 开发者 Python
通过标签清理微信好友:Python自动化脚本解析
微信已成为日常生活中的重要社交工具,但随着使用时间增长,好友列表可能变得臃肿。本文介绍了一个基于 Python 的自动化脚本,利用 `uiautomator2` 库,通过模拟用户操作实现根据标签批量清理微信好友的功能。脚本包括环境准备、类定义、方法实现等部分,详细解析了如何通过标签筛选并删除好友,适合需要批量管理微信好友的用户。
102 7
|
5月前
|
监控 Ubuntu API
Python脚本监控Ubuntu系统进程内存的实现方式
通过这种方法,我们可以很容易地监控Ubuntu系统中进程的内存使用情况,对于性能分析和资源管理具有很大的帮助。这只是 `psutil`库功能的冰山一角,`psutil`还能够提供更多关于系统和进程的详细信息,强烈推荐进一步探索这个强大的库。
75 1
|
监控 数据安全/隐私保护 Python
用 Python 写摸鱼监控进程,用这个!
继打游戏、看视频等摸鱼行为被监控后,现在打工人离职的倾向也会被监控。 有网友爆料称知乎正在低调裁员,视频相关部门几乎要裁掉一半。而在知乎裁员的讨论区,有网友表示企业安装了行为感知系统,该系统可以提前获知员工跳槽念头。
227 0
用 Python 写摸鱼监控进程,用这个!
|
监控 Python
|
监控 Python Windows
python os.startfile python实现双击运行程序 python监控windows程序 监控进程不在时重新启动
用python监控您的window服务 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://world77.blog.51cto.com/414605/782935     最近比较烦,研发给的pc服务版本在虚拟机上已经开始给客户使用了,服务老是莫名的死翘翘,客户不停的电话给我,搞的我心情很差,于是在一个下午,静下心来,用python写了个简单的监控进程的脚本,当发现进程消失的时候,立即调用服务,开启服务。
2094 0

热门文章

最新文章