在Ubuntu下的Shell ps命令

时间:2011-04-11 20:27:56

标签: shell ubuntu

我对shell脚本有疑问。我想尽可能具体。所以,我必须编写一个监视shell脚本,我必须在一个文件中写入所有运行vi命令的用户,而不是一分钟。我真的不知道这个方法,除了我应该使用ps命令。我有这样的事情:

ps -ewo“%t%u%c%g”| grep'\< vi>'

有了这个,我得到了时间和运行vi命令的用户。问题是我真的不知道如何解析这个命令的结果。有人可以帮忙吗?所有答案都表示赞赏。感谢

4 个答案:

答案 0 :(得分: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; }'

注意,你不必为“vi”grep,你可以使用“ps -C procname”。

答案 1 :(得分: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获取更好的统计数据

请注意,通过将<60更改为例如,您可以轻松地将测试切换为59秒或3分11秒。 <191(3分11秒)

答案 2 :(得分:0)

如果你有Ruby(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

答案 3 :(得分: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;
}'