python3 implementation of process monitoring with the same name in windows

Keywords: svn shell Windows

python3 implementation of process monitoring with the same name in windows

The SVN service of the old SVN server of the company is often shut down unexpectedly. It needs to write a simple monitoring script to monitor it;

First, multiple SVN services use different ports. Use the wmic command to check the ports occupied by all SVN processes to determine whether the target service is alive. The wimc command is as follows:
wmic process where caption="svn.exe" get commandline /value
Then, the ports in the standard output are taken out by regular to compare;

def get_alive_port(program):
    """
        //Get the port occupied by the target program
        :param program {string} Goal process
        :return portlist {list} List of ports occupied by the target process
    """
    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

After monitoring, it is found that the SVN service is not shut down unexpectedly, but the SVN program has been accessed for a long time and takes up too much memory. It needs to be monitored with the help of psutil;

def howmuch_memory(program):
    """
        //Monitor whether the target process memory exceeds the threshold, and close if it exceeds the threshold
    """
    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("The following error occurred:{0}".format(e))
            continue

Posted by dud3r on Wed, 01 Apr 2020 10:03:26 -0700