python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python实现windows下同名进程监控

python3实现windows下同名进程监控

作者:qq_22766903

这篇文章主要为大家详细介绍了python3实现windows下同名进程监控,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文