我想使用“last -t”,然后按照要求以 YYYYMMDDHHMMSS 格式将当前日期/时间传递给它。我知道如何获取当前日期/时间的唯一方法是通过“日期”,但它以错误的格式将其传回。
last-t 还使用时间范围来显示自时间范围以来谁已登录,当我将其转换为正确的格式时,我将如何从当前时间中减去 1 分钟。
最后是否有一个命令可以显示那些注销的人?
查看
date
联机帮助页。您可以以各种格式输出日期和时间,包括您想要的格式。记得引用论点。
为了减去1分钟,我个人会使用Python和
datetime
模块,用它来计算时间很容易。
不知道注销部分。
1 NOW=`date`
2 MINAGO=$((-1 + `date -d "$NOW" "+%Y%m%d%H:%M:%S" | cut -d: -f2 `))
3 MINAGO=`printf "%02i" $MINAGO`
4 MINAGO=`date -d "$NOW" "+%Y%m%d%H:%M:%S"| sed s/:.*:/$MINAGO/`
5 last -t $MINAGO
您必须更具体地说明显示注销者的含义,因为最后一个是向您显示谁注销以及他们何时注销。如果他们尚未登录,他们就会退出。您还需要了解什么?无论如何,可以在 /etc/shadow 中查找真实帐户并从该列表中删除仍然登录的用户。 例如:
getent shadow |sort -t: -k2,2 | awk -F: '($2 !="*") && ($2 !="!") { print $1 }'
请记住,只有 root 可以读取 /etc/shadow
刮掉上面的内容;
last -t $(
date -d @$(( -60 + `date +%s` )) +%Y%m%d%H%M%S
)
| grep still
例如
$ last -t $( date -d @$(( -60 + `date +%s` )) +%Y%m%d%H%M%S) | grep still
* pts/4 * Sat Sep 7 02:20 still logged in
* pts/44 * Fri Sep 6 19:08 still logged in
* pts/8 * Fri Sep 6 11:26 still logged in
* pts/32 * Fri Sep 6 09:37 still logged in
* pts/60 * Wed Sep 4 08:06 still logged in
* pts/34 * Tue Sep 3 23:26 still logged in
* pts/5 * Tue Sep 3 12:38 still logged in
* pts/37 * Mon Sep 2 10:59 still logged in
* pts/46 * Sun Sep 1 21:29 still logged in
这个问题分为三个部分。以下答案基于 AWS Linux 2023 是
1a>
last
命令的时间格式不可配置。有一个名为 --time-format
的命令行选项。 --time-format
的可用选项为 notime
、short
、full
或 iso
。最接近您的要求的是 iso
选项
last --time-format iso
1b> 另一种方法是将输出通过管道传输到
cut
或 awk
并按照您想要的方式格式化。下面给出了示例代码。
#!/bin/bash
# Exclude pattern viz. 'system boot' user and 'wtmp' tailer
exclude_pattern="system boot|wtmp"
# get the last log info into a variable
last_log=$(last --time-format iso | egrep -v "${exclude_pattern}")
echo "$last_log" | while IFS= read -r last_log_line; do
iso_start_time=""
iso_end_time=""
# read the info into variables
user=$(echo $last_log_line | cut -f1 -d\ )
pty=$(echo $last_log_line | cut -f2 -d\ )
ip=$(echo $last_log_line | cut -f3 -d\ )
duration=$(echo $last_log_line | cut -f7 -d\ )
# read the iso format of start time
iso_start_time=$(echo $last_log_line | cut -f4 -d\ )
if date -d "$iso_start_time" >/dev/null 2>&1; then
# set the date format to YYYYMMDDHHMMSS
out_start_time=$(date -d "$iso_start_time" +"%Y%m%d%H%M%S")
fi
# read the iso format of end time
iso_end_time=$(echo $last_log_line | cut -f6 -d\ )
if date -d "$iso_end_time" >/dev/null 2>&1; then
# set the date format to YYYYMMDDHHMMSS
out_end_time=$(date -d "$iso_end_time" +"%Y%m%d%H%M%S")
fi
# print the output
if [[ $out_end_time == "" ]]; then
echo $user $pty $ip $out_start_time - "still logged in"
else
echo $user $pty $ip $out_start_time - $out_end_time $duration
fi
done
2> 您可以使用
since
命令的 last
选项来获取特定范围的输出。
last -s -1minute
last -s -1days
last -s -1month
3>
last
命令还显示注销时间。