linux系统自动记录登陆用户的操作命令
说明:该脚本名字叫trace—login(自定义),通过将如下脚本命令写进/etc/profile,每次用户通过ssh登陆命令行并执行操作命令,即可记录执行操作。执行操作的记录会被重定向到/var/log/history的目录下,并生成以登陆用户的用户名为文件夹,将执行操作的记录追加到该文件夹中。
具体部署操作:
- 将如下代码copy到服务器中,例如命令为trace-login.txt的文件
- cat trace-login >> /etc/profile #将trace-login里面内容追加到全局环境变量配置文件
- source /etc/profile #刷新全局环境变量配置文件
#-----------------------trace_login--------------------------------
USER_IP=$(echo -e "`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`")
IP=$(who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g')
USER=$(whoami)
USER_NAME=`echo -e "$(whoami)"`
HISTFILESIZE=100000
HISTSIZE=4096
HISTTIMEFORMAT="%F %T $USER_IP $USER_NAME "
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
DT=`date +%Y%m%d_%H%M`
chmod 600 /var/log/history/${LOGNAME}/* 2>/dev/null
export PROMPT_COMMAND='{ date "+%Y-%m-%d %T ###### $(history 1 | { read x cmd; echo "$cmd";})"; } >> /var/log/history/${LOGNAME}/${DT}_${USER}_${IP}'
最终效果:
文件记录路径:
[root@linshi history]# ll /var/log/history/
total 60
d-wx------ 2 root root 45056 Feb 7 17:47 root
[root@linshi history]# ll /var/log/history/root|more
total 2
-rw------- 1 root root 1559 Jan 24 2022 20220124_1741_root_30.1.1.1 #生成的记录以年、月、日、小时、分钟,具体操作用户以及登陆服务器时的源ip地址
-rw------- 1 root root 6787 Jan 24 2022 20220124_1754_root_30.1.1.5
文件具体内容:
[root@test root]# cat 20220216_0925_root_30.1.1.1
2022-02-16 09:25:40 ###### 2022-02-15 21:37:23 30.18.145.100 root ssh 30.1.1.4
2022-02-16 09:25:40 ###### 2022-02-15 21:37:23 30.18.145.100 root ssh 30.1.1.4
2022-02-16 09:25:41 ###### 2022-02-15 21:37:23 30.18.145.100 root ssh 30.1.1.5
2022-02-16 09:26:09 ###### 2022-02-16 09:25:54 30.18.145.100 root tail -f /tmp/skq-6789.log
2022-02-16 09:26:37 ###### 2022-02-16 09:26:21 30.18.145.100 root ssh 30.1.1.100

浙公网安备 33010602011771号