2017-05-08 63 views
0

我寫這是捕獲操作系統上運行的「RM」過程中一個小碼報告..下面是代碼捕捉運行超過30分鐘的過程,併發送

bash-4.1$ cat CheckRM1.py 
#!/usr/bin/python 
import subprocess 

def Check_Ps(): 
    ps = subprocess.Popen(['ps', '-eo' 'pid,user,args,etime='], stdout=subprocess.PIPE) 
    output = ps.communicate()[0] 
    for line in output.splitlines(): 
     if 'rm' in line: 
      pss = (line) 
      print pss 

Check_Ps() 

When i run the code, it generate the output in the below form: this basically giving the process ID number(PID) , user name, command & at last the total time since the process running. This time basically uses the format [[dd-]hh:]mm:ss . In my case its running more than 9 mins.

bash-4.1$ ./CheckRM1.py 
22908 karn  rm -i e ee q r w     09:19 

現在我正在尋找運行更多30分鐘的過程,並將其打印出來併發送郵件。因此,任何想法如何捕獲只有超過30分鐘的過程,將不勝感激。

注意:我正在使用python 2.7。

+0

要監視由操作系統或創建的過程? – bigbounty

+0

@bigbounty,我想在多個系統上運行此代碼,並希望通過運行任何用戶來捕獲「rm」進程,然後想要查看超過30分鐘的時間,然後將其存儲到變量中,以便發送出去作爲警報。 – rocky1981

+0

你沒有回答我的問題。正確地閱讀問題,然後回答 – bigbounty

回答

1

Question: ... how to capture only process running more than 30 mins

你已經接近,split(..由空格,例如線時間

import re 

time_str = line.split(' ')[-1] 
# format [[dd-]hh:]mm:ss 
time_items = [int(e) for e in re.split('[-:]', time_str)] 

dd = 0 
if len(time_items) == 2: 
    hh = 0 
    mm,ss = time_items 
elif len(time_items) == 3: 
    hh, mm, ss = time_items 
else: 
    dd,hh,mm,ss = time_items 

print('Process is running {} Days {} Hours {} Minutes {} Seconds'.format(dd,hh,mm,ss)) 

time_minutes = (hh*60) + mm 
if time_minutes >= 30: 
    # do report 

測試使用Python 3.4.2

+0

@stofl,thnx讓我檢查。 – krock1516

+0

你的代碼它的運行我只是把'int'換成'str',因爲它是爲int引發錯誤,比如'ValueError:int()的無效文字,它的基數爲10:'51 -18',而且我希望進程名稱爲打印時間超過30分鐘。 – krock1516

+0

我忘了把這些數據,現在我已經編輯了與輸出數據和產生這個命令和變量的主要職位。 – krock1516