linux 实时监控shell执行命令 记录日志

linux 系统 实时监控shell执行命令 记录日志

原理

在linux系统中,history命令可以输出历史命令,历史命令默认保存在文件~/.bash_history中。

扩展

HISTFILESIZE 定义了在 .bash_history 中最大保存命令的记录数 HISTSIZE 定义了向.bash_history文件中追加的最大行数,一般这两个值相等

方式1

创建日志目录并且设置权限

mkdir -p /var/log/his

修改profile文件

export HISTFILE="/var/log/his/(date′+(who am i | sed "s/[ ][ ]*/ /g"); history 1 | { read x date time cmd; echo "date{
          
   time} user{
          
   cmd}"; } >> $HISTFILE

方式二

把下面的代码粘贴到 /etc/profile 文件 后面可以设置 HISTFILE 变量把登录信息记录到 /var/log/history目录下

##################################
#          bash history          #
##################################
# IP
USER_IP=`who am i 2>/dev/null| awk {print $NF}|sed -e s/[()]//g`
if [ "$USER_IP" = "" ]
then
  USER_IP=`hostname`
fi

# history_log output dirctory
if [ ! -d /var/log/history ]
then
   mkdir /var/log/history
   chmod 777 /var/log/history
fi
# history_log output file
if [ ! -d /var/log/history/${LOGNAME} ]
then
    mkdir /var/log/history/${LOGNAME}
    chmod 300 /var/log/history/${LOGNAME}
fi

# var
HISTSIZE=4096
export HISTSIZE
DT=`date "+%Y%m%d_%H%M%S"`
export DT
HISTFILE="/var/log/history/${LOGNAME}/$DT.${USER_IP}.hist"
export HISTFILE
chmod 600 /var/log/history/${LOGNAME}/*.hist 2>/dev/null
umask 022

参考

经验分享 程序员 微信小程序 职场和发展