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:
<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实现监控linux性能及进程消耗性能的方法
  • 使用Python的Supervisor进行进程监控以及自动启动
  • linux系统使用python监控apache服务器进程脚本分享
  • 写了个监控nginx进程的Python脚本
(0)

相关推荐

  • python实现监控linux性能及进程消耗性能的方法

    本文以实例形式实现了python监控linux性能以及进程消耗性能的方法,具体实现代码如下: # -*- coding: utf-8 -*- """ Created on Tue Jun 10 10:20:13 2014 @author: lifeix """ from collections import OrderedDict import time import os def cpuinfo(): lines = open('/proc/s

  • 写了个监控nginx进程的Python脚本

    复制代码 代码如下: #!/usr/bin/env python import os, sys, time while True: time.sleep(3) try: ret = os.popen('ps -C nginx -o pid,cmd').readlines() if len(ret) < 2: print "nginx process killed, restarting service in 3 seconds." time.sleep(3) os.system(

  • 使用Python的Supervisor进行进程监控以及自动启动

    做服务器端开发的同学应该都对进程监控不会陌生,最近恰好要更换 uwsgi 为 gunicorn,而gunicorn又恰好有这么一章讲进程监控,所以多研究了下. 结合之前在腾讯工作的经验,也会讲讲腾讯的服务器监控是怎么做的.同时也会讲下小团队又该怎么敏捷的解决. 下面按照监控的方法依次介绍. 一.按照进程名监控 在腾讯内部所有server都是要打包发布的,而在打包过程中是需要填写要监控的进程名,然后在crontab中定时通过ps查询进程是否存在. 这种方法是比较简单的方法,但是考虑到很多进程会在启

  • linux系统使用python监控apache服务器进程脚本分享

    crtrl.py监控Apache服务器进程的Python 脚本 复制代码 代码如下: !/usr/bin/env Python import os, sys, time while True: time.sleep(4) try: ret = os.popen('ps -C apache -o pid,cmd').readlines() if len(ret) < 2: print "apache 进程异常退出, 4 秒后重新启动" time.sleep(3) os.system

  • 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 pytho

  • python 监控某个进程内存的情况问题

    目录 python监控某个进程内存 python监控进程并重启 分析了具体思路 相关代码很简单 python监控某个进程内存 测试场景: 某个客户端程序长时间运行后存在内存泄漏问题,现在开发解决了需要去验证这个问题是否还存在,并要求出具相应测试验证报告. 手段: 需要有一个工具能够实时去获取该程序进程一直运行下占用内存,CPU使用率情况. 方法: python去实现这么个监控功能 import sys import time import psutil sys.argv # get pid fr

  • Python守护进程和脚本单例运行详解

    本篇文章主要介绍了Python守护进程和脚本单例运行,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 一.简介 守护进程最重要的特性是后台运行:它必须与其运行前的环境隔离开来,这些环境包括未关闭的文件描述符.控制终端.会话和进程组.工作目录以及文件创建掩码等:它可以在系统启动时从启动脚本/etc/rc.d中启动,可以由inetd守护进程启动,也可以有作业规划进程crond启动,还可以由用户终端(通常是shell)执行. Python有时需要保证只运行一个脚本实例,以避

  • python监控进程状态,记录重启时间及进程号的实例

    本脚本为本人在性能测试过程中编写,用于对进程状态的监控,也可以用于日常的监控,适用性一般,扩展性还行 # -*- coding: UTF-8 -*- # author=baird_xiang import os import time import re import copy nginxRestart_num= -1 nginxReload_num= -1 logSender_num= -1 es_num= -1 nginxParent_pid=[] nginxChild_pid=[] log

  • 用shell脚本监控进程是否存在 不存在则启动的实例

    用shell脚本监控进程是否存在 不存在则启动的实例,先上代码干货: #!/bin/sh ps -fe|grep processString |grep -v grep if [ $? -ne 0 ] then echo "start process....." else echo "runing....." fi ##### processString 表示进程特征字符串,能够查询到唯一进程的特征字符串 0表示存在的 $? -ne 0 不存在,$? -eq 0 存

  • python psutil监控进程实例

    我就废话不多说了,直接上代码吧! import psutil import subprocess import os from os.path import join,getsize import re import time from subprocess import PIPE counter=0 filesize_last=0 def restart_process(): haspro = 0 all_process_name = psutil.pids(); for pid in all

  • 利用Python写个摸鱼监控进程

    目录 监控键盘 监控鼠标 记录监控日志 完整代码 总结 继打游戏.看视频等摸鱼行为被监控后,现在打工人离职的倾向也会被监控. 有网友爆料称知乎正在低调裁员,视频相关部门几乎要裁掉一半.而在知乎裁员的讨论区,有网友表示企业安装了行为感知系统,该系统可以提前获知员工跳槽念头. 而知乎在否认了裁员计划的同时,也声明从未安装使用过网上所说的行为感知系统,今后也不会启用类似软件工具. 因为此事,深信服被推上风口浪尖,舆论关注度越来越高. 一时间,“打工人太难了”“毫无隐私可言”的讨论层出不穷. 今天就带大

  • 基于Python 的进程管理工具supervisor使用指南

    Supervisor 是基于 Python 的进程管理工具,只能运行在 Unix-Like 的系统上,也就是无法运行在 Windows 上.Supervisor 官方版目前只能运行在 Python 2.4 以上版本,但是还无法运行在 Python 3 上,不过已经有一个 Python 3 的移植版 supervisor-py3k. 什么情况下我们需要进程管理呢?就是执行一些需要以守护进程方式执行的程序,比如一个后台任务,我最常用的是用来启动和管理基于 Tornado 写的 Web 程序. 除此之

  • Python中进程和线程的区别详解

    Num01–>线程 线程是操作系统中能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位. 一个线程指的是进程中一个单一顺序的控制流. 一个进程中可以并发多条线程,每条线程并行执行不同的任务. Num02–>进程 进程就是一个程序在一个数据集上的一次动态执行过程. 进程有以下三部分组成: 1,程序:我们编写的程序用来描述进程要完成哪些功能以及如何完成. 2,数据集:数据集则是程序在执行过程中需要的资源,比如图片.音视频.文件等. 3,进程控制块:进程控制块是用来记录进程的外部

  • python监控nginx端口和进程状态

    本文实例为大家分享了python监控nginx端口和进程状态的具体代码,供大家参考,具体内容如下 #!/usr/local/bin/python # coding:utf-8 import psutil import sys import os # 获取主机名称 def hostname(): sys = os.name if sys == 'nt': hostname = os.getenv('computername') return hostname elif sys == 'posix'

随机推荐