用于指定用户的Shell脚本已登录到计算机

时间:2012-11-27 14:31:38

标签: shell

username=$1
freq=$2

checkuser()
{
  if who grep "$1"
  then
  sleep 60
  fi
}

if [ -n "$1" ]
then
echo "Enter username"
read username
checkuser
echo -e "$1 is logged on \a"
echo -e "$1 logged in at `date`">>LOG
checkuser
else
echo "User is not logged on"
fi

我需要在我的代码中集成第二个参数,允许用户指定脚本应该在什么时间之后检查谁登录。我将它设置为当前60秒,这需要是默认频率。我试图使用另一个功能但无济于事。我想到了这样的事情......

if [ "$2" -ne 0 ]
then
freq=$2
else
freq=60

感谢William,这非常有帮助!!我稍微更改了代码并想出了这个。我现在需要添加第三个参数“X”,当选择它时只是向LOGFILE而不是屏幕发送消息。我做了一次尝试,但没有按预期行事。

 username=$1
 freq=${2:-10}
 X=$3

 checkuser()
 {
 whoami|grep "$1";
 }

 while checkuser "$username"
 do
 echo -e "$1 is logged on \a"
 echo "$1 logged in at `date`">>LOGFILE
 sleep $freq
 exit 0
 done
 echo "User is not logged in"

 if [ "$3" -ne 1 ]
 then
 echo "$1 logged in at `date`"LOGFILE
 fi

3 个答案:

答案 0 :(得分:1)

username=$1
freq=${2:-60} # Set a default frequency

checkuser(){ who | grep -q "$1"; }

while ! checkuser "$username"; do
    echo "User is not logged on"    
    sleep $freq
done
echo "$1 is logged on"

另请注意,您可以简化用户名的设置:

username=${1:-$( echo "Enter username: "; read u; echo $u; )}

答案 1 :(得分:0)

echo 'Enter id'
read id
res=`who | grep "$id" | wc -l` 
if [ $res -eq 0 ]
then
    echo 'user is not logged in'
else
    echo 'user is logged in'
fi

答案 2 :(得分:0)

一个简单的shell脚本,它将用户名作为输入,并确定用户当前是否已登录。

if [[ $# -eq 0 ]]; then
    echo "Usage: " $0 "username"
    exit 1
fi

result="$(who | grep $1 | wc -l)"

if [[ $result -gt 0 ]]; then
    echo "$1 is currently logged in"
else
    echo "$1 is not logged in"
fi

exit 0