Bash 监控会话

Bash 监控会话

我想编写一个 BASH 来监控给定用户名的会话登录时间。这是我目前所拥有的。我希望它能够像任何用户一样工作

( lastlog awk ' {print $1 } ' | tail -n +2)
do
NOW=$(date +%s)
USR=$(lastlog | awk '( print $1, $5, $6, $9 )' | grep $U)
USRDATE=$(echo $USR | cut -d":" -f2)
(( USRDATE = $(date --date ""$USRDATE" +%s) / 86400 ))
(( NOW = NOW / 86400 ))
(( DAYS = NOW - USRDATE ))
echo "The user $U: logged in $DAYs days ago"
done

答案1

我会完全跳过 lastlog 并查看who命令。这实际上可以完成您要求的所有操作:

$ who
oli      tty7         2013-09-20 14:33 (:0)
oli      pts/0        2013-09-20 14:33 (:0)
oli      pts/2        2013-09-21 22:00 (:0)
oli      pts/4        2013-09-25 20:09 (:0)
oli      pts/5        2013-09-24 11:02 (:0)

w也相当不错,但是登录时间有点口语化,所以不太适合脚本:

$ w
 20:13:15 up 5 days,  5:39,  5 users,  load average: 0.49, 0.53, 0.45
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
oli      tty7     :0               Fri14    5days  8:35m  0.03s /bin/sh /usr/bin/startkde
oli      pts/0    :0               Fri14    5days  0.00s  3:36  kdeinit4: kded4 [kdeinit]                      
oli      pts/2    :0               Sat22    3days  0.08s  0.08s /bin/bash
oli      pts/4    :0               20:09    3.00s  0.08s  0.00s w
oli      pts/5    :0               Tue11    5:45m  2:42   2:42  node /usr/bin/grunt watch

相关内容