Linux服务器在使用过程中,经常会有除自己之外的其他人员使用。并不是每个人都对Linux服务器特别熟悉,难免会有一些操作导致服务器报错。
因此,监控Linux服务器的操作并记录下来,是非常有必要的!
history是查询当前连接所操作的命令,通过编写以下内容添加至/etc/profile的原有内容之后,将每个连接的操作都进行记录,并保存在特定位置。
- 打开终端,输入以下命令
vi /etc/profile
- 追加以下内容
#history record
history
RQ=`date "+%Y%m%d"`
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 /tmp/record ]
then
mkdir /tmp/record
chmod 777 /tmp/record
fi
if [ ! -d /tmp/record/${LOGNAME}/${RQ} ]
then
mkdir -p /tmp/record/${LOGNAME}/${RQ}
chmod 300 /tmp/record/${LOGNAME}/${RQ}
fi
export HISTSIZE=8192
SJ=`date "+%H:%M:%S"`
export HISTFILE="/tmp/record/${LOGNAME}/${RQ}/${USER_IP}@${LOGNAME}.$SJ"
chmod 600 /tmp/record/${LOGNAME}/*record* 2>/dev/null
- 保存并退出(按ESC,输入:wq!),并执行以下命令,使得编写的配置生效。
source /etc/profile
将操作记录保存在/tmp/record/用户名/日期/登录IP@用户名.时间,
例如:/tmp/record/root/20170801/192.168.108.140@root.16:02:41
历史操作命令已经记录在上述文件中,可以直接查看。
但是为了查询方便,可以再编写一个查询的脚本。
- 使用root用户登录,创建bin文件夹,命令如下:
mkdir /root/bin
- 创建查询脚本record:
vi /root/bin/record
添加以下内容
#!/bin/sh
user=${LOGNAME}
time=`date +%Y%m%d`
ip=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`
while [ $# -gt 0 ]
do
case $1 in
-u|--user) user=$2;
shift 2;
;;
-t|--time) time=$2;
shift 2;
;;
-p|--ip) ip=$2;
shift 2;
;;
-l|--list)
export HISTFILE="/tmp/record/$user/$time";
echo $HISTFILE;
ls $HISTFILE;
exit 0;
;;
*)
echo "usage: record [ -u|-t|-p|-t| --user|--time|--ip|--list]
-u --user: username;
-t --time: The date required to query;
-p --ip: Query the IP ;
-l --list: Show the list of record files.
Notice:
-l --list: This parameter must be used as the last parameter,
and only the display of the file path,
not the file contents."
exit 0;
;;
esac
done
export HISTFILE="/tmp/record/$user/$time"
echo Path: $HISTFILE/ | tr -d '\n'
ls $HISTFILE | grep $ip
#export RecordFile="$HISTFILE/$ip*"
#echo Contents:
#cat $RecordFile
保存并退出,使用root用户在任意目录下面都可以使用record命令进行查询历史操作记录。
注:只有当连接退出之后,才会保存操作记录。不指定参数的话,会使用当前连接的默认参数!
具体参数使用情况如下:
默认查询(查询当前用户,当前IP的历史连接的操作记录)
record
将执行相应命令显示出来文件,进行打开,即可查看。(此处我已进行修改,除了l或者list参数以外,可以自动展示出来历史记录。由于历史操作太多,暂时进行注释。)