Linux命令记录脚本

2016年4月7日14:33:08 评论 6,494

在Linux中有个很重要的命令可以帮助我们记录曾经使用过的命令,对于后续排错或者入侵检测都是很有用。本文中把配置整理成一个脚本,直接运行脚本即可生效

#!/bin/bash
/bin/cp /etc/bashrc /etc/bashrc.`date +"%Y-%m-%d-%s"`
sed -i '/timestamp_history/,+10d' /etc/profile
grep "HISTTIMEFORMAT" /etc/profile >/dev/null || echo "export HISTTIMEFORMAT='%F %T '" >> /etc/profile
sed -i '/timestamp_history/,+10d' /etc/bashrc

/bin/cat >> /etc/bashrc <<EOF
timestamp_history(){
export infodate=\`date "+ %c"\`    #记录时间
export infohis=\`history 1|cut -c 8-\`  #记录运行命令
export user_ip=\`who -u am i 2>/dev/null | awk '{print \$NF}' | sed -e 's/[()]//g'\`   #记录用户ip
export user=\`who -u am i 2>/dev/null | awk '{print \$1}'\`  ##记录用户
echo \$infodate" => "\$user_ip" => "\$user" => "\$infohis >> /var/log/.history-timestamp
}
export PROMPT_COMMAND=timestamp_history
export HISTTIMEFORMAT="\`whoami\` "
export HISTCONTROL=ignoreboth
EOF

#每月备份一次
echo '/bin/mv /var/log/.history-timestamp /var/log/.history-timestamp.`date +"%Y-%m-%d-%s"`
touch /var/log/.history-timestamp
chmod 0772 /var/log/.history-timestamp' > /etc/cron.monthly/backup_history
/bin/chmod 755 /etc/cron.monthly/backup_history

运行后日子格式如下图:

Linux命令记录脚本

做好的脚本可以放在一台web上面,其他机器直接通过命令去获取安装

wget -O - http://ip/setHis.sh | sh ; source /etc/bashrc
weinxin
聂扬帆博客
一个分享IT运维相关工作经验和实战技巧的个人博客

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: