You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CentOS系统中记录命令历史日志?附Ubuntu实现参考

在CentOS中记录命令历史日志的方法

其实和你在Ubuntu里的操作逻辑一致,只是部分配置细节需要适配CentOS的环境,具体步骤如下:

1. 修改bash全局配置文件

CentOS的全局bash配置文件是/etc/bashrc(也可以用/etc/profile,前者仅针对bash生效,后者对所有shell生效),在文件末尾添加以下内容:

export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'

这段代码会在每次执行命令后,把当前用户、进程ID、执行的命令以及命令返回值,通过logger工具发送到local6日志通道。

2. 配置rsyslog定向命令日志

创建/etc/rsyslog.d/bash.conf文件,写入以下规则:

local6.* /var/log/commands.log

这会告诉rsyslog服务,把local6通道的所有日志内容都写入/var/log/commands.log文件中。

3. 配置日志轮转**(可选但推荐)**

编辑/etc/logrotate.d/rsyslog文件,添加一行:

/var/log/commands.log

这样logrotate会按照系统默认的日志轮转规则处理这个命令日志文件,避免日志文件过大占用过多磁盘空间。

4. 重启rsyslog服务生效配置

CentOS 7及以上版本用systemctl命令重启:

sudo systemctl restart rsyslog

如果是CentOS 6及更早版本,使用service命令:

sudo service rsyslog restart

验证效果

执行几个测试命令后,查看日志文件就能看到记录内容了:

Feb 2 06:20:12 centos-server root [2345]: ls -l /var/log [0]
Feb 2 06:20:18 centos-server user1 [2367]: sudo systemctl status rsyslog [0]
Feb 2 06:20:25 centos-server user1 [2367]: cat /var/log/commands.log [0]

注意:已登录的用户需要重新登录,或者执行source /etc/bashrc命令,才能加载新的bash配置。

内容的提问来源于stack exchange,提问作者jawad846

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:19:14