有时候我们需要对线上用户操作记录进行历史记录待出现问题追究责任人,,但Linux系统自带的history命令用户有自行删除权限,那怎么设置可以让用户的操作记录实时记录,并保证普通用户无权删除呢?
1.创建系统用户shell命令行操作记录日志存放位置

mkdir -p /var/log/userlogin/records/
chmod 777 /var/log/userlogin/records/
chmod +t /var/log/userlogin/records/

2.vim /etc/profile 在最后添加下面的代码

if [ ! -d  /var/log/userlogin/records/${LOGNAME} ]
then
mkdir -p /var/log/userlogin/records/${LOGNAME}
chmod 300 /var/log/userlogin/records/${LOGNAME}
fi

export HISTORY_FILE="/var/log/userlogin/records/${LOGNAME}/bash_history"

export PROMPT_COMMAND='{ date "+%Y-%m-%d %T ##### $(who am i |awk "{print \$1\" \"\$2\" \"\$5}") #### $(history 1 | { read x cmd; echo "$cmd"; })"; } >>$HISTORY_FILE'
source /etc/profile

3.测试验证

[root@master01 local]# source /etc/profile
[root@master01 local]# cd /var/log/userlogin/records/
[root@master01 records]# ls
root
[root@master01 records]# cd root/
[root@master01 root]# ls
bash_history
[root@master01 root]# cat bash_history 
2018-06-04 03:41:30 ##### root pts/0 (10.0.0.1) #### source /etc/profile
2018-06-04 03:41:40 ##### root pts/0 (10.0.0.1) #### cd /var/log/userlogin/records/
2018-06-04 03:41:41 ##### root pts/0 (10.0.0.1) #### ls
2018-06-04 03:41:43 ##### root pts/0 (10.0.0.1) #### cd root/
2018-06-04 03:41:43 ##### root pts/0 (10.0.0.1) #### ls
[root@master01 root]# su - postgres
[postgres@master01 ~]$ echo 12345 >>test001
[postgres@master01 ~]$ ls
pg_dump.sh  test001
[postgres@master01 ~]$ cat test001 
12345
[postgres@master01 ~]$ logout
[root@master01 root]# pwd
/var/log/userlogin/records/root
[root@master01 records]# ls
postgres  root
[root@master01 records]# cd postgres/
[root@master01 postgres]# ls
bash_history
[root@master01 postgres]# cat bash_history 
2018-06-04 03:42:17 ##### root pts/0 (10.0.0.1) #### cd ..
2018-06-04 03:42:18 ##### root pts/0 (10.0.0.1) #### ls
2018-06-04 03:42:29 ##### root pts/0 (10.0.0.1) #### echo 12345 >>test001
2018-06-04 03:42:31 ##### root pts/0 (10.0.0.1) #### ls
2018-06-04 03:42:36 ##### root pts/0 (10.0.0.1) #### cat test001