2013-04-03 143 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