Bash
1 前言
一个问题,一篇文章,一出故事。
今天有个使坏需求,让小孩工作日玩不了电脑。
2 最佳实践
2.1.1 创建脚本
vim ~/scripts/monitorUser.sh
加入如下内容,
#!/bin/bash
# 要监控的用户列表,用空格分隔(驼峰式命名)
targetUsers="will"
# 获取当前星期几
currentDay=$(date +%w)
for targetUser in $targetUsers; do
if w -h | grep -q "^${targetUser}\s"; then
if [ "$currentDay" -ge 1 ] && [ "$currentDay" -le 5 ]; then
echo "$(date): 工作日禁止 ${targetUser} 用户登录,系统将自动注销..."
userSessions=$(w -h | grep "gnome-session-binary" | awk '{print $2}')
for session in $userSessions; do
echo "正在注销 ${targetUser} 用户的会话: $session"
echo pkill -KILL -t "$session"
done
pkill -KILL -u "$targetUser" 2>/dev/null
else
echo "$(date): 周末允许 ${targetUser} 用户使用"
fi
fi
done
2.2 创建脚本触发
crontab -e
加入如下内容,
*/5 * * * * bash ~/scripts/monitorUser.sh
没有评论