我正在尝试编写一个shell脚本,允许我登录到远程计算机,以查看哪些用户运行vtwm进程超过14天。这是我到目前为止所写的内容。
有两个问题
此活动进程可能有多个用户。如何将所有这些保存在变量中?
如何确定哪一个已登录超过14天?
编写以下代码时假设只有一个用户具有活动的vtwm进程。但它不起作用,因为grep命令无法识别变量$ u。 所以我永远无法获得用户登录的日期。由于grep问题,我无法让mth1和day1工作。
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 :(得分:2)
假设所有这些环境都是Linux(您没有提及),下面的代码可能对您有所帮助。
ps -o etime, user, cmd
x
=> ps a -o ...
示例如何调用此脚本:bash ./mytest.sh 5 bash
,将 +5天显示 bash 会话。
# 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 cinacio@jdivm04 "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