如何在 Linux 中记录每个 shell 命令

问题:如何将 shell 命令历史重定向到 Syslog?

有几种方法可以做到这一点。
我们可以尝试使用以下 3 种方法中的任何一种:

方法 3 - 通过脚本命令

此外,如果我们只想记录单个终端会话,只需尝试如下 'script' 命令,它也易于使用且非常有用。

  1. 要开始记录,只需运行:
# script /tmp/screen.log
  1. 现在你可以启动你的 bash 命令了。
    完成后,我们可以退出:
# exit

然后它将所有会话保存到文件 /tmp/screen.log

  1. 验证输出:
# cat /tmp/screen.log

例如:

[root@hostname ~]# script /tmp/screen.log
Script started, file is /tmp/screen.log
[root@hostname ~]# date
Thu Apr 9 00:28:26 EDT 2020
[root@hostname ~]# whoami
root
[root@hostname ~]# exit
exit
Script done, file is /tmp/screen.log
[root@hostname ~]# cat /tmp/screen.log
Script started on Thu 09 Apr 2020 12:28:23 AM EDT
[root@hostname ~]# date
Thu Apr 9 00:28:26 EDT 2020
[root@hostname ~]# whoami
root
[root@hostname ~]# exit
exit
Script done on Thu 09 Apr 2020 12:28:42 AM EDT
[root@hostname ~]#

方法 1 - 通过 rsyslog 服务

要使用 rsyslog 记录每个 shell 命令,只需按照以下步骤操作:

  1. 新建rsyslog配置文件,定义日志文件路径。
    例如: /var/log/commands.log 。
# vi /etc/rsyslog.d/bash.conf
local6.* /var/log/commands.log
  1. 编辑用户的 ~/bashrc 。
    注意:我们需要编辑每个需要此类日志的用户的 ~/bashrc 。
# vi ~/.bashrc
whoami="$(whoami)@$(echo $SSH_CONNECTION | awk '{print }')"
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$whoami [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'

例如:

[root@hostname ~]# cat ~/.bashrc | tail -n2
whoami="$(whoami)@$(echo $SSH_CONNECTION | awk '{print }')"
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$whoami [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'
[root@hostname ~]#
  1. 重启rsyslog服务
# systemctl restart rsyslog

请参阅下面的日志格式示例:

[root@hostname ~]# date
Thu Apr 9 00:26:11 EDT 2020
[root@hostname ~]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)
[root@hostname ~]# tail -2 /var/log/commands.log
Apr 9 00:26:11 hostname root: root@x.x.x.x [1643]: date [0]
Apr 9 00:26:18 hostname root: root@x.x.x.x [1643]: cat /etc/redhat-release [0]
[root@hostname ~]#
www. On IT Road .com

方法 2 - 通过 bash shell 选项

  1. 将'shopt -s syslog_history'添加到系统启动/etc/profile或者个人初始化文件~/.bash_profile中。
    例如:
[root@hostname ~]# cat /etc/profile | grep shopt
shopt -s syslog_history
  1. 注销并重新登录以反映此选项。

  2. 日志示例:

[root@hostname ~]# pwd
/root
[root@hostname ~]# date
Thu Apr 9 01:26:46 EDT 2020
[root@hostname ~]# tail -2 /var/log/messages
Apr 9 01:26:46 hostname -bash: HISTORY: PID=1345 UID=0 date
Apr 9 01:26:52 hostname -bash: HISTORY: PID=1345 UID=0 tail -2 /var/log/messages
[bob@hostname ~]$ tail -f /var/log/messages
Apr 9 01:26:45 hostname -bash: HISTORY: PID=1345 UID=0 pwd
Apr 9 01:26:46 hostname -bash: HISTORY: PID=1345 UID=0 date
Apr 9 01:26:52 hostname -bash: HISTORY: PID=1345 UID=0 tail -2 /var/log/messages
日期:2020-09-17 00:13:42 来源:oir作者:oir