2013-04-03 132 views
1

我正在尝试编写一个shell脚本,允许我登录到远程计算机以查看哪些用户正在运行vtwm进程超过14天。这是我迄今写的。在Shell脚本中的grep

有两个问题

  1. 有可能是这个活动的进程不止一个用户。我如何将它们全部保存在一个变量中?

  2. 如何确定哪一个已登录超过14天?

下面的代码是在假设只有一个用户具有活动vtwm进程的情况下编写的。但它不起作用,因为grep命令不能识别变量$ u。 所以我永远不会得到用户登录的日期。我不能让mth1和day1工作,因为与grep的问题。

u=$(ssh host "w | grep vtwm | cut -d' ' -f1") 
echo "USER:"$u 
if [ -n "$u" ] then   
mth1=$(who | grep -i $u | cut -d' ' -f10 | cut -d'-' -f2) 
mth2=$(date +"%m") 
day1=$(who | grep -i $u | cut -d' ' -f10 | cut -d"-" -f2) 
day2=$(date +"%d") 
if [ $mth1==$mth2 ] then 
#do something 
elif[ $mth1!=$mth2 ] then 
#do something 
fi 
fi 
+0

这是令人困惑的代码。变量'$ u'由ssh'ing派生到另一台机器,但是'$ mth1'和'$ day1'是基于对'who'的本地调用? – danfuzz 2013-04-03 23:25:08

+0

用'set -vx'打开shell解析功能。你会更容易看到你的代码开始失败的地方和原因。对不起,说,也是太多的代码,你说的目标是什么。看看使用'awk'作为一个过滤器来减少对'who'的调用数量为1X。祝你好运。 – shellter 2013-04-04 01:26:36

回答

2

假设所有环境都是Linux(您没有提到过),下面的代码可能会对您有所帮助。

  • 识别过程的时候,经常ps -o etime, user, cmd
  • 脚本接收2个参数,天PROC的限制搜索
  • PS时,显示所有进程,不管有TTY分配或不...
    如果您需要使用TTY限制进程删除x =>ps a -o ...
  • 将ssh命令调整到您的环境。

实例怎么称呼这个脚本:bash ./mytest.sh 5 bash,将显示庆典与5天会议。

# mytest.sh 
#--debug-only--# set -xv 

[ $# -ne 2 ] && echo "please inform : <#of_days> <regexp>" && exit 1 
# receive the # of days 
vLimit=$1 
# name of proc to search 
vProc=$2 

vTmp1=/tmp/tmp.myscript.$$ 

# With this trap , the temp file will be erased at any situation, when 
# the script finish sucessufully or interrupted (kill, ctrl-c, ...) 
trap "rm $vTmp1 2>/dev/null ; exit" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

# ps manpage : 
# etime  ELAPSED elapsed time since the process was started, in the form [[DD-]hh:]mm:ss. 

ssh [email protected] "ps ax -o etime,user,command | grep -i '$vProc' " >$vTmp1 
while read etime user cmd 
do 

    # if not found the dash "-" on etime, ignore the process, start today... 
    ! echo "$etime" | grep -q -- "-" && continue 
    vDays=$(echo "$etime" | cut -f1 -d-) 
    [ -z "$vDays" ] && continue 
    if [ $vDays -ge $vLimit ]; then 
    echo "The user $user still running the proc $cmd on the last $vDays days...." 
    fi 
done < $vTmp1 

#--debug-only--# cat $vTmp1 
+0

非常好。但是,为什么不把ssh写入'while while read ...'。祝你好运。 – shellter 2013-04-04 01:27:54

+0

嗨@shellter,是的,他可以使用'ssh ... |同时阅读'这将避免$ vTmp1治疗。在我看来,写作的方式很容易理解,它是如何工作,自定义代码,然后删除不需要的。擦除总是很容易.. – ceinmart 2013-04-04 02:26:21