key区分登录用户

脚本放 /etc/profile.d,会默认登录的时候执行, 类似于

#!/bin/bash
# filename: /etc/profile.d/set_log_file.sh
#增加 关于history操作记录按key分离的实现
if [ ! -d /var/log/login/histlog ];then
/bin/mkdir -p /var/log/login/histlog
/bin/chmod 777 /var/log/login/histlog
fi shopt -s histappend
history -a
# your_name 最好是英文
# ssh-rsa kn5SZaPKpEvtX2LmGBDMddltLRgS14OCy3y8KLdHvMfBuhIdroDs9M3GVDUNEvZLelwh0zTRViaxS6BLHgDxHlImXEQ43OrsuUA46oYVW/O5kMJpQXLjBf7mQas/17y8c5XQmTzZbVknusIPxWBf+CKluFi3RtdTmVXLe48FaF9rg2J3bffxR2jlF7fGQTE4ABh6G99hKdtCh/2zhz7rpsJhnqDIpucwPz6anfdrptJUUfSQeRC4gSQxATwmmE1L7EW5tfWpJCKIfg/45pAIfCFKCof/HZpdBRUNLmn9+ktzGFrE47Q== your_name
# NAME_OF_KEY=$(ssh-add -L | awk '{ print $3 }' ) # 如果key注释是英文,可以直接用这个简单的方法,如上
NAME_OF_KEY=$(ssh-add -L|awk '{print $2}' | xargs -i grep '{}' ~/.ssh/authorized_keys |awk '{print $3}') # 获取登录的key的注释,一般是登录key的人的名字,最好英文 USER=$(whoami) # 获取登录的用户
if [ -n "${USER}_$NAME_OF_KEY" ];then
if [ ! -f /var/log/login/histlog/"${USER}_$NAME_OF_KEY" ];then
touch /var/log/login/histlog/"${USER}_$NAME_OF_KEY"
fi export HISTFILE="/var/log/login/histlog/${USER}_$NAME_OF_KEY"
fi # echo 导致scp失败,但是在debug的时候,可以把下面echo的注释打开
#echo HISTFILE="/var/log/login/histlog/${USER}_$NAME_OF_KEY"
export PROMPT_COMMAND='history -a;history -w'
export HISTTIMEFORMAT='%Y%m%d-%H:%M:%S: '

日志生成的路径:

[root@ns_10.2.1.242 profile.d]$ cd /var/log/login/histlog/
[root@ns_10.2.1.242 histlog]$ pwd
/var/log/login/histlog
[root@ns_10.2.1.242 histlog]$ ls
root_xupeiyuan

ssh-add命令

[root@ns_10.2.1.242 etc]$ ssh-add -L
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4NWBVjQzaQChJiwx8IUMH5Og6f/0atgxZkn5SZaPKpEvtX2LmGBDMddltLRgS14OCy3y8KLdHvMfBuhIdroDs9M3GVDUNEvZLelwh0zTRViaxS6BLHgDxHlImXEQ43OrsuUA46oYVW/O5kMJpQXLjBf7mQas/17y8c5XQmTzZbVknusIPxWBf+CKluFi3/RtdTmVXLe48FaF9rg2J3bff/xR2jlF7fGQTE4ABh6G99hKdtCh/2zhz7rpsJhnqDIpucwPz6anfdrptJUUfSQeRC4gSQxATwmmE1L7EW5tfWpJCKIfg/45pAIfCFKCof/HZpdBRUNLmn9+ktzGFrE47Q== xupeiyuan

查看历史命令

查看所有登录的人执行的命令:

#!/bin/bash
#服务器history按key分离后操作记录查看脚本 cd /var/log/login/histlog/
rm -fr /tmp/usrname.history
ls /var/log/login/histlog/|while read usrname
do
filename=$usrname
exec 5<$filename
while read line <&5
do
echo $line|awk '{if ($1 ~/^#[0-9]+/) {split ( $0 , time, "#"); printf (" '$usrname' " strftime("%Y-%m-%d_%H:%M:%S",time[2])" ")} else print $0 }'>>/tmp/usrname.history
done
done
sort -k2 /tmp/usrname.history |cat -n

上面脚本的结果:

[root@ns_10.2.1.242 histlog]$ sh ~/view_history.sh
1 root_xupeiyuan 2015-03-13_10:27:04 ls
2 root_xupeiyuan 2015-03-13_10:27:10 cd /etc/profile.d/
3 root_xupeiyuan 2015-03-13_10:27:12 ls
4 root_xupeiyuan 2015-03-13_10:27:14 vim set_log_file.sh
5 root_xupeiyuan 2015-03-13_10:27:58 ssh-add -L
05-08 15:01