Search code examples
pythonunixprocessfindps

How to find a unix process in Python


I would to find if the output of 'ps' command contain the process 'smtpd' The problem is that various busybox need different ps command! some need ' ps x ', other need ' ps w ' and other only the ' ps '

How i can make a universal algorithm that try all 'ps' possibilities ?

Example:

linex=''
foo=os.popen('ps')
for x in foo.readlines():
   if x.lower().find('smtpd') != -1:
     // SOME SCRIPT STUFF on linex string...
return linex

linex=''
foo=os.popen('ps w')
for x in foo.readlines():
   if x.lower().find('smtpd') != -1:
     // SOME SCRIPT STUFF on linex string...
return linex

linex=''
foo=os.popen('ps x')
for x in foo.readlines():
   if x.lower().find('smtpd') != -1:
     // SOME SCRIPT STUFF on linex string...
return linex

Solution

  • Check this:

    Process list on Linux via Python

    /proc is the right place for you to find what you want

    import os
    
    pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
    
    for pid in pids:
        try:
            cmd = open(os.path.join('/proc', pid, 'cmdline'), 'rb').read()
            if cmd.find('smtpd') != -1:
                print "PID: %s; Command: %s" % (pid, cmd)
        # process has already terminated
        except IOError:
            continue