Linux服务器记录并查询历史操作记录
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Linux服务器记录并查询历史操作记录
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
然后保存并退出,执⾏以下命令,使得编写的配置⽣效。
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 $1in
-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参数以外,可以⾃动展⽰出来历史记录。
由于历史操作太多,暂时进⾏注释。
)。