| 系統 | history 輸出 |
|---|---|
| CentOS 6 | 294 2017-01-06 16:46:48 root clear 含時間、用戶 |
| CentOS 7 | 1268 history 僅有序號與命令 |
原因:CentOS 7 默認未設置 HISTTIMEFORMAT 環境變量。
echo 'export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S `whoami` "' >> /etc/profile
source /etc/profile
關鍵細節:引號內結尾有空格,確保時間戳與命令間有分隔,否則顯示粘連。
[root@bdkyr data]# history 10
1273 2017-01-05 19:40:18 root history
1274 2017-01-05 19:40:27 root clear
1275 2017-01-05 19:40:29 root cat /etc/redhat-release
1276 2017-01-05 19:40:35 root history -n 10
1277 2017-01-05 19:40:39 root history 10
1278 2017-01-05 19:41:12 root cat /etc/profile
1279 2017-01-05 19:42:16 root vim /etc/profile
1280 2017-01-05 19:42:26 root source /etc/profile
1281 2017-01-05 19:42:28 root history
1282 2017-01-05 19:42:42 root history 10
完美顯示:序號 時間戳 用戶 命令
| 參數 | 作用 |
|---|---|
n | 顯示最近 n 條記錄,如 history 10 |
-c | 清空當前 Shell 會話歷史記錄(不寫入文件) |
-a | 將當前會話新增歷史追加寫入 ~/.bash_history |
-r | 從歷史文件讀取記錄到當前會話記憶 |
-w | 將當前會話記憶寫入歷史文件 |
-d offset | 刪除指定偏移量的記錄 |
-p | 歷史擴展不執行僅打印 |
-s | 將參數作為單條記錄追加到歷史列表 |
# /etc/profile 或 ~/.bashrc 追加
export HISTSIZE=10000 # 內存中保存條數
export HISTFILESIZE=20000 # 文件中保存條數
export HISTCONTROL=ignoredups:erasedups # 忽略重複、刪除歷史中重複
export HISTIGNORE="ls:cd:clear:history:pwd" # 忽略高頻無價值命令
shopt -s histappend # 多終端退出時追加不覆蓋歷史文件
PROMPT_COMMAND="history -a; history -r" # 每條命令執行後即時同步文件
配置後,多終端操作歷史實時共享,審計追溯無遺漏。
~/.bash_history 可被用戶篡改,關鍵系統建議配置 auditd 或 syslog 遠程收集命令審計日志。HISTTIMEFORMAT 格式支持 strftime 所有佔位符,可自定義如 %F %T %z(含時區)。一行配置,讓 history 從「命令備忘錄」進化為「安全審計利器」。