lundi 9 mars 2020

Iterating through list of processes to check if PID exists with Python subprocess

I'm creating a Python program to monitor the processes on a server once an hour, to see if it can return the PID. To do this, I made a function that uses subprocess to call pgrep -f on any name submitted to it. If it returns a process, the function evaluates to true; otherwise, it returns false.

import subprocess
import psutil


def check_essentials(name):
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    pid = response.split()
    if len(pid) == 0:
        print("unable to find PID")
        return False
    else:
        print("PID is %s" % pid)
        return True

essentialApps = ['ProfileService','aflaf']
sendEmail=False

for x in essentialApps:
    check_essentials(x)
    if check_essentials == False:
        print("Unable to find PID for %s. Sending email alert" % x)
        sendEmail = True
    else:
        print("Found PID for %s" % x)

I then set up a for loop to have it iterate through a list of process names(essentialApps) and see if it can return anything for them. If not, sendEmail is set to true.

In testing this, however, I'm finding that the else statement is always being called, regardless of whether or not the app exists. When I call this program (python alert.py), I get the following output:

PID is [b'11111']
Found PID for ProfileService 
unable to find PID #This is expected
Found PID for aflaf #This should be "Unable to find PID for aflaf"

I'm sure it is something simple, but can anyone tell me why it is not evaluating check_essential correctly?

Also, is there anyway to do this with psutil? I'm reading that this should be used over subprocess, but I'm not able to find anyway to specifically mimic pgrep -f name or ps -aux | grep name. Thats important, as I have multiple Java applications running on the machine, and the program name that psutil seemed to see was always 'java', not 'ProfileService'.

Aucun commentaire:

Enregistrer un commentaire