在linux系统的环境下,不管是root用户还是其它的用户只有登陆系统后用进入操作我们都可以通过命令history来查看历史记录,可是假如一台服务器多人登陆,一天因为某人误操作了删除了重要的数据。这时候通过查看历史记录(命令:history)是没有什么意义了。那有没有什么办法实现通过记录登陆后的IP地址和某用户名所操作的历史记录呢?答案:有的。
 编辑 /etc/profile,在最后添加:

  1. PS1="`whoami`@`hostname`:"'[$PWD]'
  2. history
  3. USER_IP=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`
  4. if [ "$USER_IP" = "" ]
  5. then
  6. USER_IP=`hostname`
  7. fi
  8. if [ ! -d /tmp/history ]
  9. then
  10. mkdir /tmp/history
  11. chmod 777 /tmp/history
  12. fi
  13. if [ ! -d /tmp/history/${LOGNAME} ]
  14. then
  15. mkdir /tmp/history/${LOGNAME}
  16. chmod 300 /tmp/history/${LOGNAME}
  17. fi
  18. export HISTSIZE=4096
  19. DT=`date "+%Y%m%d_%H%M%S"`
  20. export HISTFILE="/tmp/history/${LOGNAME}/${USER_IP} history.$DT"
  21. chmod 600 /tmp/history/${LOGNAME}/*history* 2>/dev/null

其实通过上面的代码不能看出来,在系统的/tmp新建个history目录,在目录中记录了所有的登陆过系统的用户和IP地址,是不是觉得很方便呢?我们还可以用这个方法来监测系统的安全性。

方法二、

========================================================

  1. 一、如果你的系统有多个用户,你想知道每个用户登录系统做了哪些操作,从那里登录的,登录时间等待一系列信息,那么请按我的做吧。
  2. 二、编辑脚本
  3. vi /etc/profile.d/accountlog.sh
  4. historyLog(){
  5. logDir=/data/accountlog
  6. dateStamp=`date +"[%F %T]"`
  7. dateDir="`date +%Y`/`date +%m`/`date +%d`"
  8. curHistory=`history 1`
  9. user=`/usr/bin/whoami`
  10. realUserInfor=`/usr/bin/who -u am i|awk '{print $1,$2,$3"~"$4,$7}'`
  11. if [ ! -e $logDir ];then
  12. mkdir -p $logDir
  13. chmod 777 $logDir
  14. fi
  15. logDateDir=$logDir/$dateDir
  16. if [ ! -e $logDateDir ];then
  17. mkdir -p $logDateDir
  18. chmod -R 777 $logDir 2>/dev/null
  19. fi
  20. accountLogDir=$logDateDir/${user:=`hostname`}
  21. if [ ! -e $accountLogDir ];then
  22. mkdir -p $accountLogDir
  23. #chmod 777 $accountLogDir
  24. fi
  25. accountLogName=${user:=`hostname`}.his
  26. accountLog=$accountLogDir/$accountLogName
  27. if [ ! -e "$accountLog" ];then
  28. touch $accountLog
  29. #chmod 777 $accountLog
  30. fi
  31. echo "$realUserInfor $dateStamp =>$curHistory" >>$accountLog
  32. }
  33. export PROMPT_COMMAND=historyLog
  34. [root@localhost ~]# chmod +x /etc/profile.d/accountlog.sh
  35. 三、以后每个用户登录的操作都会在/data/accountlog记录
  36. [root@localhost data]# cd accountlog/
  37. [root@localhost accountlog]# ls
  38. 2012
  39. [root@localhost accountlog]# cd 2012/
  40. [root@localhost 2012]# ls
  41. 01  02  03  04  05  06  07
  42. [root@localhost 2012]# cd 07/
  43. [root@localhost 07]# ls
  44. 09  10  12  13  14  15  16  19  20  21
  45. [root@localhost 07]# cd 21
  46. [root@localhost 21]# ls
  47. root