2014-09-12 58 views
0

我會發現'ps'命令的輸出是否包含進程'smtpd' 問題是,各種busybox需要不同的ps命令! 有些需要'PS X',其他需要'PS W'和其他只有'PS'如何在Python中找到unix進程

我怎麼能做出一個通用算法來嘗試所有'PS'的可能性?

例子:

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 
+0

你真的需要這個嗎?除非寫入TTY,否則任何兼容POSIX的'ps'都不應該被截斷。另外,我不能相信不同的busybox版本具有完全不同的'ps'版本(你確定你在某些機器上沒有真正單獨的'ps'命令而不是busybox內置版本?)另外,如果你使用標準('-'-prefixed)標誌而不是試圖使用GNU或BSD擴展,'ps -ww'應該適用於任何'ps'-GNU,BSD或其他。 – abarnert 2014-09-13 00:34:47

回答

1

檢查:

Process list on Linux via Python

的/ proc是您正確的地方找到你想要

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 
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",..."]) 

是你可以做的一種方式這

,如果你可能有多個匹配處理

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