在命令 history 中显示时间戳


 history 是一条非常实用的 shell 命令,可以显示出之前在 shell 中运行的命令,配合 last 显示之前登录的用户,就可以追溯是哪个用户执行了某些命令。

last
...
mysurface    tty7         :0               Mon Oct  6 20:07 - down   (00:00)
reboot   system boot  2.6.24.4-64.fc8  Mon Oct  6 20:06          (00:00)
mysurface    pts/8        10.168.28.44     Mon Oct  6 17:42 - down   (01:58)
mysurface    pts/7        :0.0             Mon Oct  6 17:41 - 19:40  (01:59)
mysurface    pts/6        :0.0             Mon Oct  6 17:27 - 19:40  (02:13)
mysurface    pts/5        :0.0             Mon Oct  6 17:27 - 19:40  (02:13)
mysurface    pts/5        :0.0             Mon Oct  6 15:52 - 15:59  (00:07)
...
    不过默认下,history 并不记录命令的执行时间,分析起来很困难。这时候可以配置 HISTTIMEFORMAT 环境变量,给 history 记录添加上时间戳:

export HISTTIMEFORMAT="%F %T "
    效果:

...
  994  2008-10-16 02:27:40 exit
  995  2008-10-16 01:12:20 iptables -nL
  996  2008-10-16 01:47:46 vi .bash_profile
  997  2008-10-16 01:47:55 history
  998  2008-10-16 01:48:03 . .bash_profile
  999  2008-10-16 01:48:04 history
 1000  2008-10-16 01:48:09 exit
 1001  2008-10-16 02:27:43 history
...
    把上面的 export 命令加入到  ~/.bashrc 或者 ~/.bash_profile  中即可在登录后自动开启 history 时间戳了~

    其实 HISTTIMEFORMAT 的格式就是 strftime 函数的格式,比如上面的  "%F %T",%F 表示显示出  Y-M-D 格式的日期,%T 表示显示出  H-M-S 这样格式的时间。更多的格式,可以参考 man strftime

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3