实时保存用户历史命令——shell脚本

实时保存linux系统下用户的历史命令
脚本如下

[root@k8s-master ~]# cat history.sh
#!/bin/bash
#sehn
USER_IP=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`
HISTDIR=/var/log/.history  #历史命令保存目录
if [ -z $USER_IP ];then
USER_IP=`hostname -I`
fi
if [ ! -d $HISTDIR ];then
mkdir -p $HISTDIR
chmod 777 $HISTDIR
fi
if [ ! -d $HISTDIR/${LOGNAME} ];then
mkdir -p $HISTDIR/${LOGNAME}
chmod 300 $HISTDIR/${LOGNAME}
fi
export HISTSIZE=4096
DT=`date +%Y%m%d_%H%M%S`
export HISTFILE="$HISTDIR/${LOGNAME}/$DT.${LOGNAME}.${USER_IP}"
export HISTTIMEFORMAT="[%Y.%m.%d %H:%M:%S]"
chmod 600 $HISTDIR/${LOGNAME}/*.history* 2>/dev/null

添加权限,我这里是实验环境,直接给了777

[root@master ~]# chmod 777 history.sh

将脚本添加至/etc/profile.d/

[root@master ~]# cd /etc/profile.d/
[root@master profile.d]# ls
256term.csh  bash_completion.sh  colorgrep.sh  colorls.sh  lang.csh  less.csh  sh.local  vim.sh      which2.sh
256term.sh   colorgrep.csh       colorls.csh   csh.local   lang.sh   less.sh   vim.csh   which2.csh
[root@k8s-master profile.d]# cp /root/history.sh .

使环境变量立即生效

[root@master ~]# source /etc/profile

测试
创建一个普通用户,登录进行一系列操作

[root@master .history]# useradd test
[root@master .history]# su test
[test@master .history]$ cd /tmp/
[test@master tmp]$ ls
vmware-root_7930-1003075826  vmware-root_8425-1713837358  vmware-root_8615-1957110343  vmware-root_8654-693800911
[test@master tmp]$ mkdir abc
[test@master tmp]$ echo "hello world" > abc/test
[test@master tmp]$ exit
exit

查看历史命令保存目录,已经生成文件

[root@master test]# pwd
/var/log/.history/test
[root@master test]# ls
20200810_215123.test.192.168.200.1

可以查看到该用户操作的历史命令的内容

[root@master test]# cat 20200810_215123.test.192.168.200.1
#1597067492
cd /tmp/
#1597067497
ls
#1597067523
mkdir abc
#1597067569
echo "hello world" > abc/test
#1597067585
exit
[root@master test]#

也可以结合crontab定期将日志保存至远端服务器

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值