linux shell历史命令记录功能怎么用

编辑: admin 分类: centos 发布时间: 2023-06-14 来源:互联网

在 linux 下面可以使用 history 命令查看用户的所有历史操作,同时 shell 命令操作记录默认保存在用户目录的 .bash_history 文件中。通过这个文件可以查询 shell 命令的执行历史,有助于运维人员进行系统审计和问题排查,同时在服务器遭受黑客攻击后,也可以查询黑客登录服务器的历史命令操作。但是黑客在入侵后,为了抹除痕迹,会删除 .bash_history 文件,这个就需要合理备份这个文件了。

默认的 history 命令只能查看用户的历史操作记录,但是不能区分每个用户操作命令的时间。这点对于问题排查相当的不方便。解决办法是在 /etc/bashrc 文件中加入以下四行来让 history 命令自动记录所有 shell 命令的执行时间:

复制代码 代码如下:

histfilesize=4000
histsize=4000
histtimeformat='%f %t'
export histtimeformat

histfilesize 表示在 .bash_history 文件中保存命令的记录总数,默认值是 1000;histsize 定义了 history 命令输出的记录总数;histtimeformat 定义了时间显示格式,该格式与 date 命令后的 “+"%f %t"” 是一样的;histtimeformat 作为 history 的时间变量将值传递给 history 命令。

高级技巧

上面那个虽然可以记录时间,但是无法作为审计目的使用,很容易被黑客篡改或者丢失。下面这种方法详细记录了登录过系统的用户、ip 地址、shell 命令以及详细操作的时间。并将这些信息以文件的形式保存在一个安全的地方,以供系统审计和故障排查。

把以下代码放入 /etc/profile 文件中,即可实现上述功能。

复制代码 代码如下:

#record history operation
user_ip=`who -u am i 2>/dev/null |awk '{print $nf}' |sed -e 's/[()]//g'`
logname=`who -u am i |awk '{print $1}'`
histdir=/user/share/.history
if [ -z $user_ip]
then
user_ip=`hostname`
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=4000

dt=`date +"%y%m%d_%h%m%s"`
export histfile="$histdir/${logname}/${user_ip}.history.$dt"
export histtimeformat="[%y.%m.%d %h:%m:%s]"
chmod 600 $histdir/${logname}/*.history* 2>/dev/null

【文章转自日本多IP服务器 http://www.558idc.com/japzq.html提供,感恩】