python实现windows下同名进程监控 python3实现windows下同名进程监控

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python实现windows下同名进程监控 python3实现windows下同名进程监控

qq_22766903   2021-03-31 我要评论

python3实现windows下同名进程监控,供大家参考,具体内容如下

公司老版的SVN服务器的svn服务经常意外关闭,需要写个简单的监控脚本监控一下;

首先多个SVN服务使用不同的端口,使用wmic命令查看所有SVN进程占用的端口以此来判断目标服务是否存活,wimc命令如下:

wmic process where caption=”svn.exe” get commandline /value

然后用正则取出标准输出中的端口,用来比对;

def get_alive_port(program):
 """
  获取目标程序占用的端口
  :param program {string} 目标进程
  :return portlist {list} 目标进程占用的端口列表
 """
 cmd = 'wmic process where caption="%s" get commandline /value' % program
 ps = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
 portlist = []
 while True:
  out = ps.stdout.readline()
  if out:
   out = out.decode("gb2312")
   templist = re.findall("[0-9]{4,5}", out)
   portlist.extend(templist)
  else:
   break
 return portlist

使用监控后发现SVN服务不意外关闭了,但是SVN程序被访问久了占用过大内存需要监控一下借助psutil来实现;

def howmuch_memory(program):
 """
  监控目标进程内存是否超过阀值,若超过则关闭
 """
 cmd = 'wmic process where caption="%s" get processid /value' % program
 ps = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
 pids = []
 while True:
  out = ps.stdout.readline()
  if out:
   out = out.decode("gb2312")
   templist = re.findall("[0-9]{3,6}", out)
   pids.extend(templist)
  else:
   break
 for pid in pids:
  try:
   p = psutil.Process(int(pid))
   p_memory = p.memory_info()
   if int(p_memory.rss / (1024 * 1024)) >= 200:
    p.kill()
  except Exception as e:
   print("出现如下错误:{0}".format(e))
   continue

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们