python3实现windows下同名进程监控,供大家参考,具体内容如下
公司老版的SVN服务器的svn服务经常意外关闭,需要写个简单的监控脚本监控一下;
首先多个SVN服务使用不同的端口,使用wmic命令查看所有SVN进程占用的端口以此来判断目标服务是否存活,wimc命令如下:
wmic process where caption=”svn.exe” get commandline /value
然后用正则取出标准输出中的端口,用来比对;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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来实现;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_22766903/article/details/79772092