监控Linux用户登录后的操作(history)

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

通过在/etc/profile里面加入以下代码就可以实现:

#PS1就是用来设置命令提示符的环境变量
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/loghistory ]
then
mkdir /tmp/loghistory
chmod 777 /tmp/loghistory
fi
if [ ! -d /tmp/loghistory/${LOGNAME} ]
then
mkdir /tmp/loghistory/${LOGNAME}
chmod 300 /tmp/loghistory/${LOGNAME}
fi
# 保存历史命令条数
export HISTSIZE=4096
DT=`date "+%Y-%m-%d_%H:%M:%S"`
# 设置保存历史命令的文件
export HISTFILE="/tmp/loghistory/${LOGNAME}/${USER_IP}.loghistory.$DT"
chmod 600 /tmp/loghistory/${LOGNAME}/*loghistory* 2>/dev/null

source /etc/profile 使用脚本生效
退出用户,重新登录(注销)
查看命令记录(本地:0.)

#export HISTFILE=/tmp/loghistory/:0.loghistory.2016-02-26_09:32:33
#history

注:这个脚本有一个缺点,如果是普通用户远程登录的,在切换的到root用户,之前普通用户的操作记录会被覆盖。暂时没想到太好的解决办法,只是很冗余的写到每个用户的.bash_profile里,如果有更好的办法欢迎交流。

你可能感兴趣的:(linux基础)