Linux的history命令增加时间戳

一般Linux的系统的history命令只会展示一个index和执行命令,但是很多时候,我们都想查看一下这个命令是是什么人,在什么时候,在哪个IP下面执行的这个命令。这个时候,我们就需要编辑一下/etc/profile这个文件。

使用vim /etc/profile在文件最后面增加2行如下所示脚本:

1
2
3
#history增加时间戳
USER_IP=`who -u -m | awk '{print $NF}'| sed 's/[()]//g'`
export HISTTIMEFORMAT="%F %T `whoami` ${USER_IP} "

然后退出编辑模式,输入source /etc/profile使文件生效。在使用history命令查看,即可看见之后的命令的执行者是哪个用户,什么时候执行的,以及是哪个ip地址。

1
2
3
4
5
6
7
[root@izbp145clkvoxcy8wk7b3uz ~]# history | tail -5
1004 2019-06-17 10:26:16 root 124.90.68.224 source /etc/profile
1005 2019-06-17 10:26:19 root 124.90.68.224 history
1006 2019-06-17 10:27:07 root 124.90.68.224 cat /etc/profile
1007 2019-06-17 10:31:05 root 124.90.68.224 hisotry | tail -5
1008 2019-06-17 10:31:12 root 124.90.68.224 history | tail -5
[root@izbp145clkvoxcy8wk7b3uz ~]#