在 /etc/profile.d 文件夹下新建文件 history_log.sh
#!/bin/bash
# careful! only root can mkdir
if [ ! -d /var/log/history ]; then
mkdir /var/log/history
chmod 777 /var/log/history
fi
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/${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 HISTFILE="/var/log/history/${LOGNAME}/${USER}@${USER_IP}_${DT}"
chmod 600 /var/log/history/${LOGNAME}/*history* 2>/dev/null
然后接着在 root 环境下source /etc/profile,否则普通用户没有权限创建文件夹
原理:
通过修改HISTFILE变量,把原本保存在 .bash_history 中的用户操作历史保存到/var/log/history中的文件夹下,
看看实际效果:
- 首先需要 root 用户创建文件夹:
/var/log/history - 作为普通(含root)用户,创建用户文件夹
- 普通用户没有对自身操作历史的访问权限,真是妙啊
[monkey@server ~]$ ls -ld /var/log/history
drwxrwxrwx 4 root root 4096 2月 8 15:55 /var/log/history
[monkey@server ~]$ ls -l /var/log/history
total 8
d-wx------ 2 monkey monkey 4096 2月 8 16:27 monkey
d-wx------ 2 root root 4096 2月 8 16:27 root
[monkey@server ~]$ ls -l /var/log/history/monkey
ls: cannot open directory /var/log/history/monkey: Permission denied
- 只有 root 用户可以访问所有用户操作历史
[root@server monkey]# ls /var/log/history/
monkey root
[root@server monkey]# ls -ld /var/log/history/monkey/
d-wx------ 2 monkey monkey 4096 2月 8 16:27 /var/log/history/monkey/
[root@server monkey]# ls -l /var/log/history/monkey/
-rw------- 1 monkey monkey 25 2月 8 16:27 monkey@xxx.xxx.195.63_20210208_16:09:58
[root@server monkey]# cat /var/log/history/monkey/monkey\@xxx.xxx.195.63_20210208_16\:09\:58
rm test
ls
sudo su
exit
- 需要注意的是,这样以来每次用户登录后的操作历史都没有保留在
.bash_history文件中,因此history命令无法查看上一次登录时执行的命令,当然这也不失为一个优点! - 如果用户在胡乱捣鼓一通后输入:
history -c,可以把自己的操作历史删除。。。
附:
| # | 权限 | rwx | 二进制 |
|---|---|---|---|
| 7 | 读 + 写 + 执行 | rwx | 111 |
| 6 | 读 + 写 | rw- | 110 |
| 5 | 读 + 执行 | r-x | 101 |
| 4 | 只读 | r– | 100 |
| 3 | 写 + 执行 | -wx | 011 |
| 2 | 只写 | -w- | 010 |
| 1 | 只执行 | –x | 001 |
| 0 | 无 | — | 000 |

被折叠的 条评论
为什么被折叠?



