用shell编写一个用户监测程序usr_monitor, 其运行格式为: usr_monitor username 其中username是用户指定的任意一个用户名。程序运行时首先列出当前系统中的已登录用户的名单,再检查指定用户是否已登录。如果已登录,则显示相应信息;如果未登录,则等待该用户登录,直到指定用户登录进入系统为止。
时间: 2024-02-24 14:57:59 浏览: 24
以下是一个简单的Shell实现,可以实现你所需的功能:
```bash
#!/bin/bash
# 获取已登录用户列表
function get_logged_users() {
who | awk '{print $1}'
}
# 检查指定用户是否已登录
function check_user() {
username=$1
logged_users=$(get_logged_users)
for user in $logged_users
do
if [ "$user" = "$username" ]
then
echo "$username is logged in."
return 0
fi
done
return 1
}
# 等待指定用户登录
function wait_for_user() {
username=$1
while true
do
if check_user $username
then
break
fi
sleep 1
done
}
# 主程序
if [ $# -lt 1 ]
then
echo "Usage: usr_monitor username"
exit 1
fi
username=$1
if check_user $username
then
exit 0
else
wait_for_user $username
exit 0
fi
```
你可以将以上代码保存为usr_monitor.sh,然后在命令行中运行:
```
$ chmod +x usr_monitor.sh
$ ./usr_monitor.sh username
```
其中username是你要监测的用户名。程序会先列出当前系统中已登录的用户,然后检查指定用户是否已登录。如果已登录,则显示相应信息;如果未登录,则等待该用户登录,直到指定用户登录进入系统为止。