0

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
Hooked
  • 84,485
  • 43
  • 192
  • 261
rocherz
  • 31
  • 1
  • 2
  • 7
  • Do you really need this? Any POSIX-compatible `ps` shouldn't be truncating lines unless writing to a TTY. Also, I can't believe different busybox versions have radically different versions of `ps` (are you sure you don't have a real separate `ps` command on some machines instead of a busybox builtin?) Plus, if you use the standard (`-`-prefixed) flags instead of trying to use the GNU or BSD extensions, `ps -ww` should work on any `ps`—GNU, BSD, or otherwise. – abarnert Sep 13 '14 at 00:34

2 Answers2

1

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
Community
  • 1
  • 1
0
def find_sys_cmds(needle,cmd,options):
    for opt in options:
        for line in os.popen("%s %s"%(cmd,opt)).readlines():
            if needle in line.lower():
                return line

print find_sys_cmds("smtpd","ps",["","x","w","aux",..."])

is one way you might do this

if you might have multiple matching processes

def find_sys_cmds(needle,cmd,options):
     for opt in options:
         for line in os.popen("%s %s"%(cmd,opt)).readlines():
             if needle in line.lower():
                    yield line

for line in find_sys_cmds("smtpd","ps",["","x","w","aux",..."]):
    print line
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179