2017-05-08 53 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

相关问题