Centos记录所有用户登录和操作的详细日志

时间:2024-01-21 11:14:45

1、起因

最近Linux服务器上一些文件呗篡改,想追查已经查不到记录了,所以得想个办法记录下所有用户的操作记录。

一般大家通常会采用history来记录,但是history有个缺陷就是默认是1000行,当然你也可以vim /etc/profile将1000修改成1000000行,但是这只是比较笼统的做法,看不到详细的用户来源已经操作记录,比如来源ip地址、操作时间、操作用户等。

所以我们不得不自己写代码来实现这样的功能。

2、自动记录脚本

在/etc/profile文件的末尾追加编写脚本如下:

#set user history
history
USER=`whoami`
USER_IP=`who -u am i >/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`
if [ "$USER_IP" = "" ]; then
USER_IP=`hostname`
fi
if [ ! -d /var/log/history ]; then
mkdir /var/log/history
chmod /var/log/history
fi
if [ ! -d /var/log/history/${LOGNAME} ]; then
mkdir /var/log/history/${LOGNAME}
chown -R ${LOGNAME}:${LOGNAME} /var/log/history/${LOGNAME}
chmod /var/log/history/${LOGNAME}
fi
export HISTSIZE=
DT=`date +"%Y%m%d_%H:%M:%S"`
export HISTFILE="/var/log/history/${LOGNAME}/${USER}@${USER_IP}_$DT"
chmod /var/log/history/${LOGNAME}/*history* 2>/dev/null

这个脚本需要放在/etc/profile文件的末尾。这里默认写了记录日志文件的根目录是:/var/log/history,这个目录需要初始化建立,然后通过“exportHISTFILE="/var/log/history/${LOGNAME}/${USER}@${USER_IP}_$DT"

”可以看到记录日志的路径是/var/log/history/${LOGNAME},所以这个目录也需要事先建立,有多少个用户,就要建立多少个目录,而且要把目录的使用权限赋予相对应的用户。

而每次用户登录到退出都会产生以用户名、登录ip地址、操作时间为文件名的文件,文件里面包含本次用户的所有操作记录。

3、用户登录验证

用其中一个用户alad登录进程操作

[alad@internal-nginx alad]$touch test_history
[alad@internal-nginx alad]$cat >> test_history << EOF
>
>
EOF
[alad@internal-nginx alad]$ls
test_history

然后退出用户(需要退出当前用户),重新登录进去日志目录/var/log/history/alad/查看有最新的记录,一次用户登录到退出就会保存成一个日志文件记录:

#进入日志目录
[alad@internal-nginx alad]$ cd /var/log/history/alad
/var/log/history/alad
#查看日志记录文件
[alad@internal-nginx alad]$ ls
alad@192.168..199_20190115_17:: alad@192.168..199_20190115_17::
#打开操作记录日志
[alad@internal-nginx alad]$ cat alad\@192.168..199_20190115_17\:\:
#
ls
#
touch
#
cat >> << EOF EOF #
ls

可以清楚的看到cat后的内容为之前操作的命令记录,并且带上时间戳!