linux 记录用户登录日志与命令执行日志

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gekkoou/article/details/83826837

vi /etc/profile 在末尾增加代码

history
USER=`whoami`
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 /var/log/history ]; then
mkdir /var/log/history
chmod 777 /var/log/history
fi
if [ ! -d /var/log/history/${LOGNAME} ]; then
mkdir /var/log/history/${LOGNAME}
chmod 300 /var/log/history/${LOGNAME}
fi
export HISTSIZE=4096
DT=`date +"%Y%m%d_%H:%M:%S"`
export HISTTIMEFORMAT="[$DT][${USER}][${USER_IP}]"
export HISTFILE="/var/log/history/${LOGNAME}/${USER}@${USER_IP}_$DT"
chmod 600 /var/log/history/${LOGNAME}/*history* 2>/dev/null

执行 source /etc/profile 使其生效

之后不同用户会在 /var/log/history 以用户名为目录名的目录, 进入对应目录后会有用户登录时间IP为名字的文件, 内容为用户执行命令的日志信息

# cd /var/log/history/
# ll
total 4
d-wx------ 2 root root 4096 Nov  7 15:37 root

# cd root
# ll
total 24
-rw------- 1 root root  800 Nov  6 17:26 [email protected]_20181106_15:09:56
-rw------- 1 root root 4411 Nov  6 18:55 [email protected]_20181106_17:40:31
-rw------- 1 root root    7 Nov  7 15:35 [email protected]_20181107_15:33:23
-rw------- 1 root root   86 Nov  7 15:37 [email protected]_20181107_15:35:27
-rw------- 1 root root  124 Nov  7 15:37 [email protected]_20181107_15:37:18

# cat [email protected]_20181107_15\:37\:18
ll
ps aux
logout





猜你喜欢

转载自blog.csdn.net/Gekkoou/article/details/83826837