欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

shell如何记录用户的IP与命令详解

程序员文章站 2022-04-25 17:00:11
记录输入的命令 history命令可以查看用户输入过的命令,一个典型history命令输出如下: 980 2017-05-29 20:17:37 cd - 9...

记录输入的命令

history命令可以查看用户输入过的命令,一个典型history命令输出如下:

980 2017-05-29 20:17:37 cd -
981 2017-05-29 20:17:41 cat index.html
982 2017-05-29 20:20:11 vim index.html
983 2017-05-29 20:39:18 cd -
984 2017-05-29 20:39:25 cd /var/log/nginx/
985 2017-05-29 20:39:27 vim access.log
986 2017-05-29 20:50:10 netstat -ntlp
987 2017-05-31 11:04:39 tmux a -t0
988 2017-05-31 11:15:42 exit
989 2017-05-31 12:32:38 tmux a -t0

记录ip

为了记录用户的ip,需要首先获取用户的登录ip。由于在用户登入期间,会话不会断开,所以只需获取一次即可。

获取ip命令: who am i | awk '{print $nf}' | sed -e 's/[()]//g'

接着按照 username@ip datetime command 的格式记录用户的命令,这需要设置histtimeformat的值。获取ip和设置命令格式结合起来:

ip=`who am i | awk '{print $nf}' | sed -e 's/[()]//g'`
export histtimeformat=$user@$ip %f %t 

为了让上述命令对所有用户生效,可将其写到/etc/profile文件中。设置完毕后(可能需要重新登录,或者用source命令重新加载/etc/profile),history命令输出如下类似结果:

412 root@8.8.8.8 2017-06-02 22:03:27 netstat -nt
414 root@8.8.8.8 2017-06-02 22:03:38 netstat -ntpl
415 root@8.8.8.8 2017-06-03 14:17:09 history
416 root@8.8.8.8 2017-06-03 14:17:30 tmux ls
417 root@8.8.8.8 2017-06-03 14:17:34 tmux
418 root@8.8.8.8 2017-06-03 14:17:49 tmux a -t0

history命令的内容保存在用户的~/.bash_history文件中,用户可随时更改或者清除。为了统一管理用户的命令记录,我们希望用户执行命令后,执行的命令能输出到某个文件内。达到这个目的需要 prompt_command 环境变量的协助。

设置prompt_command将用户的上一条命令log到syslog里面去:

export prompt_command="history 1 | logger -t cmd_log -p user.notice"

logger命令将信息输出到/var/log/messages中。任意输入一个命令,然后打开/var/log/messages,会看到已经记录在案。/var/log/messages文件只有root有权限访问,从而达到了记录用户ip和命令的目的。

如果你熟悉syslog,可以将命令记录输出到单独的文件中。这需要在logger命令的-p选项中指定工具名称和等级,例如local2.notice,然后编辑/etc/rsyslog.conf,将local2的信息输出到单独文件: local2.* /var/log/command.log,最后重启rsyslog服务。

通过如上设定,即可在用户无感知的情况下log用户的ip、时间和操作命令。

对用户来说,如何绕过?可以有两种方式:

  1. 将命令写到脚本,执行脚本;
  2. unset prompt_command变量。

参考

https://askubuntu.com/questions/93566/how-to-log-all-bash-commands-by-all-users-on-a-server

http://moper.me/ssh-audit-chats.html

http://zhu8337797.blog.163.com/blog/static/170617549201222912830483/

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。