mingk 发表于 2013-9-4 09:03:42

Windows监控进程服务器IIS进程状态解决CPU暴满造成服务器运行缓慢 Python版

之前写了bat脚本来解决服务器IIS进程造成CPU暴满状态之后感觉不胜满意,且不效率。后发现用Python的脚本比bat高效且安全不会存在误杀现象,现将其分享与大家其程序和源码我放在了百度网盘,如果有要用到的可以下载直接放到任务计划中去每5分钟运行一次监视,并记录其操作日志。这样即使服务器IIS进程造成CPU暴满也不会导致服务器暴慢而影响其它应用运行。
脚本主要用到了psutil、os 和logging三个模块
编译成exe的执行文件地址:
http://pan.baidu.com/share/link?shareid=2975465880&uk=3591480333
源码脚本文件地址:
http://pan.baidu.com/share/link?shareid=3035212689&uk=3591480333


#!/bin/bash/env python
# -*- coding: cp936 -*-
##########################################################
# 说 明:从应用进程占用CPU状态查杀其占用CPU资源超过80%的相应应用进程
# 作 者:网上管家婆运维工程师--沙砾
#QQ :442405
# 日 期:2013-08-30 Pm.
# Good Luck To You!
##########################################################
import psutil
import os
import time
import logging
def KillProcess():
    os.kill(pid,2)

def ProcessLog():
    conf={}
    conf["name"]="debug"
    conf["filename"]="ProcessKill.log"
    conf["format"]="[%(asctime)s]: %(message)s"
    conf["datefmt"]="%Y-%m-%d %H:%M:%S"
    conf["level"]=0
    logger=logging.getLogger(conf["name"])
    handler=logging.FileHandler(conf["filename"])
    fmt = logging.Formatter(conf["format"],conf["datefmt"])
    handler.setFormatter(fmt)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    LogTime=time.localtime()
    LogTimeF='%d-%d-%d %d:%d:%d' % (LogTime.tm_year,LogTime.tm_mon,LogTime.tm_mday,LogTime.tm_hour,LogTime.tm_min,LogTime.tm_sec)
    logger.debug(pid)
    logger.info(FilePath)
    logger.warning("The end of this process has been!!!")
#####################################################################################################
if __name__ == '__main__':
    pl=psutil.get_pid_list()
    r=[]
    for pid in pl:
      try:
            p=psutil.Process(pid)
            r.append((pid,p.name,p.get_cpu_percent()))
            FilePath=p.get_open_files()
            CpuPercent=p.get_cpu_percent()
            if (p.name == 'w3wp.exe') and (CpuPercent >=80):
                KillProcess()
                ProcessLog()
      except:
            pass

q2009a06z22 发表于 2013-9-4 15:23:23

我真想亲口管你爷爷叫声:爹!

yllplay 发表于 2013-9-4 17:46:29

所有的男人生来平等,结婚的除外。

czhtr 发表于 2013-9-4 22:11:55

老天,你让夏天和冬天同房了吧?生出这鬼天气!

50010623 发表于 2013-9-5 06:55:35

不要在一棵树上吊死,在附近几棵树上多试试死几次~

wyyy721 发表于 2013-9-6 01:22:05

走,MM,咱们化蝶去……

x625802392 发表于 2013-9-6 05:48:18

要是我灌水,就骂我“三个代表”没学好吧。
页: [1]
查看完整版本: Windows监控进程服务器IIS进程状态解决CPU暴满造成服务器运行缓慢 Python版