Linux 监控用户行为

/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中的文件夹下,

看看实际效果:

  1. 首先需要 root 用户创建文件夹:/var/log/history
  2. 作为普通(含root)用户,创建用户文件夹
  3. 普通用户没有对自身操作历史的访问权限,真是妙啊
[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
  1. 只有 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
  1. 需要注意的是,这样以来每次用户登录后的操作历史都没有保留在 .bash_history 文件中,因此 history 命令无法查看上一次登录时执行的命令,当然这也不失为一个优点!
  2. 如果用户在胡乱捣鼓一通后输入: history -c,可以把自己的操作历史删除。。。

附:

#权限rwx二进制
7读 + 写 + 执行rwx111
6读 + 写rw-110
5读 + 执行r-x101
4只读r–100
3写 + 执行-wx011
2只写-w-010
1只执行–x001
0000
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值