如何提取登录历史记录?


94

我需要知道特定用户的登录历史记录(即登录和注销时间),如何在Linux中提取特定日期范围的历史记录?

Answers:


133

您可以尝试以下last命令:

last john 

它打印出用户john的登录/退出历史记录。而跑步

last

打印所有用户的登录/退出历史记录。


5
在大多数Linux发行版中,这仅返回当月的值。
ewwhite

42

如果您需要回溯到一个月以上的历史记录,可以/var/log/wtmp.1使用以下last命令读取文件。

last -f wtmp.1 john将显示user上个月的登录历史记录john

最后的日志输出不太沉重并且相对容易解析,因此我可能会将输出传递给grep以查找特定的日期模式。

last john | grep -E 'Aug (2[0-9]|30) '显示8月20日至30日。或类似的东西:

last -f /var/log/wtmp.1 john | grep -E 'Jul (1[0-9]|2[0-9]|30) '为用户获取7月10日至30日john


21

如何在Linux中提取特定日期范围的登录历史记录?

列出所有从8月25日到28日登录的用户的示例:

last | while read line
do
    date=`date -d "$(echo $line | awk '{ print $5" "$6" "$7 }')" +%s`
    [[ $date -ge `date -d "Aug 25 00:00" +%s` && $date -le `date -d "Aug 28 00:00" +%s` ]] && echo $line
done
  • awk '{ print $5" "$6" "$7 }'last输出中提取相应列的日期时间
  • +%s 将日期时间转换为大纪元时间
  • -ge 代表大于或等于
  • -le 代表小于或等于

您也可以使用来为特定用户执行此操作last <username>


1
那真是个丑陋的表情。由于last输出可读性强,grep会更干净吗?
ewwhite

3
您可以grep从“ 8月15日09:00”到“ 8月25日21:00”吗?
量子

1
OP没有要求时间范围。
ewwhite

1
@ewwhite表达式对我来说看起来很漂亮,如果您不喜欢bash语法的外观,那么该网站可能不适合您。
ekerner

1
@ekerner你是对的。我会去别的地方;)
ewwhite
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.