2011-04-11 79 views
0

我有一個關於shell腳本的問題。我試圖儘可能具體。所以,我必須編寫一個監視shell腳本,在該腳本中,我必須在文件中寫入所有運行vi命令的用戶,而不是一分鐘。除了我應該使用ps命令之外,我對這種方法並不瞭解。我有這樣的事情:Ubuntu下的Shell ps命令

ps -ewo「%t%u%c%g」| grep'\ < vi>'

與此我得到時間和運行vi命令的用戶。問題是我真的不知道如何解析這個命令的結果。任何人都可以幫忙嗎?所有的答案表示讚賞。由於

回答

0

這是我會怎麼做:

ps fo "etime,user" --no-heading --sort 'uid,-etime' $(pgrep '\<vi\>') | 
    perl -ne '($min,$sec,$user) = (m/^\s+(\d\d):(\d\d)\s+(\w+)$/mo); 
       print "$user\t$min:$sec\n" unless ((0+$min)*60+$sec)<60' 

釘在| cut -f1 | uniq| cut -f1 | uniq -c得到一些更好的統計

注意的方式,這是制定很容易測試切換到59秒或3分鐘11秒,如果您願意,可以將<60更改爲eg <191(用於3m11s)

0

如果你有紅寶石(1.9+)

#!/usr/bin/env ruby 

while true 
    process="ps eo user,etime,args" 
    f = IO.popen(process) #call the ps command 
    f.readlines.each do|ps| 
     user, elapsed, command = ps.split 
     if command["vi"] && elapsed > "01:00" 
      puts "User #{user} running vi for more than 1 minute: #{elapsed}" 
     end 
    end 
    f.close 
    sleep 10 # sleep 10 seconds before monitoring again 
end 
1

我會用awk:

ps eo user,etime,pid,args --no-heading -C vi | awk '{MIN=int(substr($2,0,2)); printf "minutes=%s pid=%d\n", MIN, $3; }' 

注意,那你沒有到grep爲 「VI」,你可以使用「ps -C procname」。

+0

'ps e'不會輸出其他用戶的進程。 'etime'可能有更多的字段,'etimes'更安全。你也不過濾1分鐘的時間。 – Andrey 2014-04-11 16:53:27

0
#!/bin/sh 
# -e   :: all processes (inluding other users') 
# -o   :: define output format 
# user   :: user name 
# etimes  :: time in seconds after the process was started 
# pid   :: process id 
# comm   :: name of the executable 
# --no-headers :: do not print column names 
ps -eo user,etimes,pid,comm --no-headers | 
awk ' 
# (...)  :: select only rows that meet the condition in() 
# $4 ~ //  :: 4th field (comm) should match the pattern in // 
# (^|\/)vim?$ :: beginning of the line or "/", then "vi", 
#    nothing or "m" (to capture vim), end of the line 
# $2 > 60  :: 2nd field (etimes) >= 60 seconds 
($4 ~ /(^|\/)vim?$/ && $2 >= 60){ 
# convert 2nd field (etimes) into minutes 
    t = int($2/60); 
# check if the time is more than 1 minute 
    s = (t > 1) ? "s" : ""; 
# output 
    printf "user %s : [%s] (pid=%d) started %d minute%s ago\n", $1, $4, $3, t, s; 
}'