用途:linux用戶操作記錄一般通過命令history來查看歷史記錄,但是如果因爲某人誤操作了刪除了重要的數據,這種情況下history命令就不會有什麼作用了。以下方法可以實現通過記錄登陸IP地址和所有用戶登錄所操作的歷史命令來記錄!
分析:首先要從命令的結果裏得到用戶名和登錄該服務器的客戶端ip地址,想想什麼命令可以查到當前登錄的用戶呢。有好多,比如w;who等都可以實現。我們這裏使用who,who的參數比較多,而且比較靈活。還涉及的系統自帶的PWD和LOGNAME還有HISTORYSIZE等。
方法:在/etc/profile配置文件的末尾加入以下腳本代碼就可以實現,因爲profile是登錄時執行的家環境。
- PS1="`whoami`@`hostname`:"'[$PWD]'
- history
- USER_IP=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`
- if [ "$USER_IP" = "" ]
- then
- USER_IP=`hostname`
- fi
- if [ ! -d /tmp/history ]
- then
- mkdir /tmp/history
- chmod 777 /tmp/history
- fi
- if [ ! -d /tmp/history/${LOGNAME} ]
- then
- mkdir /tmp/history/${LOGNAME}
- chmod 300 /tmp/history/${LOGNAME}
- fi
- export HISTSIZE=4096
- DT=`date +"%Y%m%d_%H%M%S"`
- export HISTFILE="/tmp/history/${LOGNAME}/${USER_IP} history.$DT"
- chmod 600 /tmp/history/${LOGNAME}/*history* 2>/dev/null
用戶從客戶機登錄這臺機器的時候都會在/tmp/history/下面建立自己的用戶名的目錄,目錄下面有每次登錄這臺機器的文件,名字格式爲ip地址\history.登錄日期_登錄時間,如192.168.10.15\ history.20130116_184144。文件裏記錄着歷史命令。