news 2026/5/25 3:17:08

Linux 安全 | 禁用敏感命令历史记录与服务器加固配置

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Linux 安全 | 禁用敏感命令历史记录与服务器加固配置

注:本文为 “Linux 命令与服务器安全加固” 相关合辑。
英文引文,机翻未校。
中文引文,略作重排。
如有内容异常,请看原文。


How to Prevent Passwords from Saving in Bash History

如何防止密码被保存到 Bash 历史记录中

Ravi SaiveLast Updated: April 30, 2026

Every Linux user eventually runs a command they’d rather not preserve – a curl with a hardcoded password, an export with an API key, or a one-liner that would confuse any sysadmin who read it three months later. Knowing how to control what ends up in your bash history is as much a security habit as locking down SSH*.
每个 Linux 用户迟早都会执行一条不想被保留的命令——比如带硬编码密码的 curl 命令、含 API 密钥的 export 命令,或是一条三个月后让系统管理员一头雾水的单行指令。学会控制 bash 历史记录的内容,是和加固 SSH 同等重要的安全习惯。

You’ve probably been there: you paste a command with a password embedded, hitEnter, and immediately wonder how many places that string just landed. Bash stores every command you type in~/.bash_historyby default, and on most systems, that file is readable by anyone who can access your account. And if you’re sharing a server with other admins, that history file is the first place anyone looks when something breaks.
你大概率遇到过这种情况:粘贴一条带密码的命令,按下回车后立刻担心这条敏感字符串会被记录到哪里。Bash 默认会把你输入的所有命令保存到~/.bash_history,在大多数系统中,任何能访问你账户的人都可以读取该文件。如果你和其他管理员共用一台服务器,出问题时,历史记录文件会是第一个被检查的地方。

The good news is thatBashgives you precise control over what it saves, when it saves it, and how to scrub individual entries.
好消息是,Bash可以让你精确控制保存哪些内容、何时保存,以及如何清除单条记录。

How Bash Stores Command in History

Bash 如何存储命令历史

Before you can control history, you need to understand whenBashwrites it. For example, during a session, every command goes into an in-memory history list first.
在控制历史记录之前,你需要了解Bash何时写入记录。例如,在一个会话期间,所有命令会先存入内存中的历史列表。

When the session ends cleanly, that list gets appended to~/.bash_historyon disk, which matters because if your terminal crashes or you close it with kill, nothing from that session gets saved.
当会话正常结束时,该列表会追加到磁盘上的~/.bash_history文件中。这一点很重要,因为如果终端崩溃或用 kill 命令关闭,本次会话的所有内容都不会被保存。

The key variables that govern this behavior live in your shell environment, and you can check them right now:
控制该行为的关键变量位于你的 shell 环境中,你可以立即查看:

echo$HISTFILEecho$HISTSIZEecho$HISTFILESIZE

Output:
输出

/home/ravi/.bash_history 1000 2000

Let me explain the command output:
我来解释一下命令输出:

  • HISTFILEis where history gets written on exit.
    HISTFILE:会话退出时历史记录写入的文件路径。

  • HISTSIZEcontrols how many commands the in-memory list holds per session.
    HISTSIZE:每个会话在内存中可保存的命令数量。

  • HISTFILESIZEcontrols how many lines the history file can grow to on disk.
    HISTFILESIZE:磁盘上历史记录文件的最大行数。

Most distros default to1000in-memory and2000on disk, so your file keeps the last2000commands across all previous sessions. Understanding that gap between “in memory” and “written to disk” is what makes the next few techniques work cleanly.
大多数发行版默认内存保存1000条、磁盘保存2000条,因此文件会保留所有之前会话的最近2000条命令。理解内存磁盘写入之间的区别,是让后续技巧干净生效的关键。

How to Prevent a Command from Being Saved in Bash History

如何防止单条命令被保存到 Bash 历史记录

The easiest way to stop Bash from saving a command in your history is surprisingly simple, just add a space before the command.
阻止 Bash 保存单条命令最简单的方法出奇地简单:在命令前加一个空格。

For example, when you type a command like this, it gets saved in your history.
例如,输入这样的命令会被保存到历史记录:

export API_KEY="supersecretkey123"

But if you add one space at the beginning:
但如果在开头加一个空格:

export API_KEY="supersecretkey123"

Bash won’t record this line at all, as long asHISTCONTROLincludesignorespace.
只要HISTCONTROL包含ignorespace,Bash 就完全不会记录这一行。

So, firt check whether it’s already set:
首先检查它是否已设置:

echo $HISTCONTROL

Output:
输出

ignoredups:ignorespace

If you seeignorespaceorignorebothin the output, you’re already covered.
如果输出中包含ignorespaceignoreboth,说明已生效。

If the variable is empty or missing, add this to your~/.bashrc:
如果该变量为空或不存在,将以下内容添加到~/.bashrc

export HISTCONTROL=ignorespace

Then reload it:
然后重新加载配置:

source ~/.bashrc

Delete a Specific Command from Bash History

从 Bash 历史记录中删除单条命令

The leading-space trick only works before you run a command, but if you already ran something and want it gone, use history-dwith the line number:
开头加空格的技巧仅在执行命令前有效。如果已经执行并想删除,可使用history -d加行号:

For example, first, list your bash history.
例如,先列出 bash 历史记录:

history

Output:
输出

497 sudo systemctl restart nginx 498 export DB_PASS="hunter2" 499 curl https://api.example.com/token 500 ls -la /etc/nginx

To delete line 498:
删除第 498 行:

history -d 498

Output:
输出

497 sudo systemctl restart nginx 499 curl https://api.example.com/token 500 ls -la /etc/nginx

The entry is gone from the in-memory list, but you’re not done yet. That deletion only lives in memory until the session ends. When Bash writes history to disk on exit, the gap closes, and your~/.bash_historyfile won’t have the entry either, as long as you don’t runhistory -amanually before closing the terminal.
该条目已从内存列表中删除,但操作还未完成。删除效果仅保留在内存中,直到会话结束。只要关闭终端前不手动执行history -a,Bash 在退出写入磁盘时,~/.bash_history中也不会有该条目。

If you want to scrub the on-disk file immediately without waiting for the session end, runhistory -wafter the deletion:
如果不想等待会话结束,想立即清除磁盘文件,删除后执行:

history -w

This writes the current in-memory list (without the deleted entry) directly to~/.bash_history, overwriting whatever was there before.
这会将当前内存列表(不含已删条目)直接写入~/.bash_history,覆盖原有内容。

Ignore Duplicate Commands in Bash History

在 Bash 历史记录中忽略重复命令

Repeated commands like ls, cd, clear, or git status fill up history fast and make it harder to find the commands you actually care about.
重复的命令如 ls、cd、clear 或 git status 会快速填满历史记录,让你更难找到真正需要的命令。

SetHISTCONTROLtoignoredupsand Bash will skip any command that matches the one immediately before it:
HISTCONTROL设置为ignoredups,Bash 会跳过与上一条完全相同的命令:

export HISTCONTROL=ignoredups

To combine both behaviors – ignore leading spaces and duplicates – useignoreboth:
如果要同时生效——忽略开头空格和重复命令——使用ignoreboth

export HISTCONTROL=ignoreboth

Add this to your~/.bashrcso it persists across sessions:
将其添加到~/.bashrc,让配置在所有会话中永久生效:

echo'export HISTCONTROL=ignoreboth'>>~/.bashrcsource~/.bashrc

Stop Saving Certain Commands in Bash History

禁止保存特定类型的命令到 Bash 历史记录

TheHISTCONTROLhandles the space-prefix trick and duplicates, butHISTIGNORElets you define specific patterns that Bash always skips. Any command matching a pattern here never enters the history list at all:
HISTCONTROL处理空格前缀和重复命令,而HISTIGNORE可让你定义 Bash 永久忽略的命令模式。匹配这些模式的命令根本不会进入历史列表:

export HISTIGNORE="ls:ls -la:cd:pwd:clear:history:exit"

Each pattern is separated by a colon. You can use glob-style wildcards too, soexport *would suppress every export command:
每个模式用冒号分隔。你也可以使用通配符,例如export *会屏蔽所有 export 命令:

export HISTIGNORE="ls*:cd*:pwd:clear:history:export *:curl *token*"

Add it to~/.bashrcto make it permanent, and source the file again. Be careful not to make the patterns too broad; if you ignoresudo *, you’ll lose the audit trail for every privileged command you’ve ever run, which creates a different kind of problem.
添加到~/.bashrc使其永久生效,并重新加载文件。注意不要把模式设置得太宽泛;如果忽略sudo *,你会丢失所有特权命令的审计轨迹,这会带来另一类问题。

Turn Off Command History Temporarily

临时关闭命令历史记录

Sometimes you want to work on a server without leaving any trace at all such as setting up credentials, auditing a config, or doing incident response on a shared box.
有时你需要在服务器上不留任何痕迹地操作,例如配置凭证、审计配置或在共享服务器上处理应急响应。

SetHISTFILEto/dev/nullfor the current session:
将当前会话的HISTFILE设置为/dev/null

export HISTFILE=/dev/null

From that point forward in the session, nothing gets written to disk. The in-memory list still builds up (so you can use the up arrow), but when the session ends, the in-memory list evaporates instead of being flushed to a file.
从此时起,本次会话的所有内容都不会写入磁盘。内存列表仍会累积(因此你可以用向上箭头翻查),但会话结束时,内存列表会直接消失,不会写入文件。

You can also combine this withunset HISTFILEif you want to be explicit, but pointing to/dev/nullis the more portable approach and works the same way on every distro.
如果你想更明确,也可以配合unset HISTFILE使用,但指向/dev/null是更通用的方法,在所有发行版上效果一致。

How to Clear the Entire History File

清空整个历史记录文件

To start clean, delete the full history file and remove all past commands.
想从头开始,清空历史文件并删除所有过往命令:

history -c && history -w
  • history -cclears the in-memory history list for the current session.
    history -c:清空当前会话的内存历史列表。

  • history -wthen writes that empty list to~/.bash_history, overwriting the file.
    history -w:将空列表写入~/.bash_history,覆盖文件。

After running this,cat ~/.bash_historyreturns nothing. The&&operator means the second command only runs if the first succeeds, so you won’t accidentally clear the file mid-session if something goes wrong.
执行后,cat ~/.bash_history会返回空内容。&&表示第一条命令成功后才执行第二条,避免出错时意外清空文件。

Conclusion

总结

You now have 5 distinct ways to control bash history: the leading-space trick for one-off sensitive commands,history -dfor post-run cleanup,HISTCONTROLfor ignoring duplicates and spaces globally,HISTIGNOREfor permanent pattern-based exclusions, andHISTFILE=/dev/nullfor session-wide suppression.
现在你掌握了 5 种控制 Bash 历史记录的方法:针对单次敏感命令的开头空格技巧、执行后清理的history -d、全局忽略重复与空格的HISTCONTROL、永久按模式屏蔽的HISTIGNORE,以及全会话禁用的HISTFILE=/dev/null

Start with addingexport HISTCONTROL=ignorebothto your~/.bashrcright now. Then think about what patterns belong in yourHISTIGNORE.
现在就把export HISTCONTROL=ignoreboth添加到~/.bashrc,然后思考哪些命令模式应该加入HISTIGNORE

If you’re regularly exporting tokens or running curl with auth headers, those belong there. It takes 5 minutes and saves you from cleaning up sensitive data later.
如果你经常导出令牌或执行带认证头的 curl 命令,这些都应该加入屏蔽列表。只需 5 分钟,就能避免后续清理敏感数据的麻烦。


Linux 防止密码泄露:Bash 历史记录安全管控 + SSH 加固

Linux 终端.bashrc安全配置与服务器安全加固:临时操作 → 单次规避 → 进阶操作 → 全局永久防护 → 事后补救 → SSH 服务器加固

一、Bash 历史记录防密码泄露操作

针对密码、API 密钥、令牌等敏感命令,提供三种层级的事前规避方案,按需选用,避免敏感信息被记录。

1.1 单次:命令前加空格(通法)

Linux 原生自带的轻量机制,无需修改配置,仅需命令开头加1 个空格,命令不会写入历史记录。

前置条件校验

该功能依赖HISTCONTROL变量,绝大多数系统默认开启,执行命令校验:

echo$HISTCONTROL

正常输出:ignoredups:ignorespace/ignoreboth,代表已生效。

实操对比
# 不安全:无空格,命令会被写入历史记录exportDB_PASS="admin123456"curlhttps://api.test.com/token-uuser:pass# 安全:开头加空格,完全不记录exportDB_PASS="admin123456"curlhttps://api.test.com/token-uuser:pass
未开启修复(永久生效)

若输出为空,手动开启空格忽略规则:

echo'export HISTCONTROL=ignorespace'>>~/.bashrcsource~/.bashrc

1.2 会话:临时关闭全局历史记录

适用于批量敏感操作、应急运维、共享服务器操作,可关闭当前终端会话所有历史写入,实现全程零留存。

原理

Bash 默认将命令写入~/.bash_history磁盘文件,修改HISTFILE指向空设备,可终止磁盘写入,内存仅临时缓存(支持上下箭头翻查),会话关闭后记录自动销毁。

实操命令
# 临时关闭当前会话所有历史记录写入exportHISTFILE=/dev/null
补充说明
  • 仅对当前终端会话生效,重启终端自动恢复默认;
  • 兼容所有 Linux 发行版,通用性极强;
  • 等效命令:unset HISTFILE,前者兼容性更优。

1.3 进阶:fc 命令批量编辑敏感指令

fc(fix command)为 Bash 内置命令,无需修改配置,支持批量编写、执行敏感命令,适合复杂多指令敏感操作场景。

基础用法

执行fc打开系统默认编辑器(nano/vim),编写多条敏感命令,保存退出后自动执行,无任何历史记录留存。

# 打开编辑器编写敏感指令fc

编辑器内示例内容:

exportAPI_KEY="test_secret_789"curl-XPOST https://api.test.com/login-H"token:xxx"
进阶修改历史命令
# 编辑并执行上一条命令fc-1# 编辑指定行号的历史命令(先 history 查行号)fc500
功能特点
  • 支持批量编写多条敏感命令,一次性执行;
  • 无需清空历史、无需修改环境变量,零副作用;
  • 系统原生内置,无需额外安装依赖。

二、Bash 历史记录全局永久安全管控

通过环境变量永久优化历史记录规则,自动过滤重复、敏感命令,规范记录大小,从根源减少泄露风险,适配所有终端会话。

2.1 环境变量参数说明

# 查看历史文件存储路径echo$HISTFILE# 查看单会话内存最大保存命令数echo$HISTSIZE# 查看磁盘历史文件最大总行数echo$HISTFILESIZE

2.2 自动忽略重复命令

# 仅忽略连续重复命令echo'export HISTCONTROL=ignoredups'>>~/.bashrc# 同时忽略空格前缀命令 + 连续重复命令echo'export HISTCONTROL=ignoreboth'>>~/.bashrcsource~/.bashrc

2.3 永久屏蔽指定敏感命令(HISTIGNORE)

自定义黑名单,匹配规则的命令直接不进入历史记录,适配日常敏感操作场景。

echo'export HISTIGNORE="ls*:cd*:pwd:clear:history:export *:curl *token*:* -u *"'>>~/.bashrcsource~/.bashrc

规则说明:自动屏蔽目录操作、清空命令、密钥导出、带密码 curl 请求等敏感指令。

2.4 自定义历史记录存储大小

# 单会话内存保存 1000 条,磁盘文件最大 2000 条(系统默认参数)exportHISTSIZE=1000exportHISTFILESIZE=2000

三、历史记录泄露事后清理方案

针对已执行的敏感命令,精准删除、全局清空两种补救方式,快速消除泄露隐患。

3.1 删除单条敏感记录

# 1. 查看历史,获取敏感命令行号history# 2. 删除指定行(示例:删除第 498 行)history-d498# 3. 立即同步至磁盘,彻底清除history-w

3.2 清空全部历史记录

# 清空内存记录 + 覆盖磁盘文件,清空所有历史记录history-c&&history-w

四、SSH 服务器安全加固

终端历史记录防泄露为前置防护,SSH 加固可提升服务器安全能力,降低密码、密钥泄露引发的入侵风险。

4.1 安全配置项

# 编辑 SSH 配置文件sudovim/etc/ssh/sshd_config

写入以下安全配置(直接全覆盖):

# 禁止 root 超级用户远程登录 PermitRootLogin no # 关闭密码登录,仅允许密钥登录 PasswordAuthentication no ChallengeResponseAuthentication no # 自定义允许登录的普通用户名(替换为自己的用户名) AllowUsers 自定义用户名 # 可选:修改默认 22 端口(1024-65535),规避暴力扫描 Port 2222

4.2 重启服务生效

sudosystemctl restart sshd

4.3 密钥登录替代密码

# 生成 ed25519 密钥,RSA 之外的可选密钥类型ssh-keygen-ted25519# 将公钥推送至远程服务器,实现免密登录ssh-copy-id 用户名@服务器IP

五、安全配置脚本部署

所有 Bash 历史记录安全配置,执行后永久生效,无需逐条手动配置。

#!/bin/bash# Bash 历史记录安全加固一键脚本echo' # 同时忽略空格前缀、重复命令 export HISTCONTROL=ignoreboth # 屏蔽日常敏感、冗余命令 export HISTIGNORE="ls*:cd*:pwd:clear:history:export *:curl *token*:* -u *" # 规范历史记录存储大小 export HISTSIZE=1000 export HISTFILESIZE=2000 '>>~/.bashrc# 重载配置立即生效source~/.bashrcecho"Bash 历史记录安全配置部署完成!"

六、总结

  1. 单次操作:命令前加空格,适配临时单条敏感指令场景;
  2. 全会话export HISTFILE=/dev/null,临时关闭所有历史写入;
  3. 批量操作fc命令编辑执行指令,无记录留存;
  4. 全局永久防护HISTCONTROL+HISTIGNORE自动过滤冗余、敏感记录;
  5. 事后补救清理history -d精准删记录,history -c全局清空;
  6. 服务器安全防护:SSH 禁用密码/root 登录,密钥登录可抵御暴力破解。

reference

  • How to Keep Passwords Out of Bash History on Linux
    https://www.tecmint.com/hide-commands-bash-history-linux/
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/25 3:11:58

数据结构:线性表和顺序表

一、线性表线性表是一种逻辑结构,表示元素与元素之间的相邻关系,顺序表和链表是一种存储结构第一个元素具有唯一后继,最后一个元素具有唯一前驱,中间的元素具有唯一的前驱和后继二、顺序表顺序表是线性表的顺序存储,用…

作者头像 李华
网站建设 2026/5/25 3:07:26

告别无效背词,家门口的科学记忆工具太实用

养娃路上,很多焦虑都来自于“费力不讨好”的学习状态。在德州,无数家庭每天都在上演同样的画面:孩子埋头抄写单词数十遍,当天记得熟练,隔天全盘遗忘;家长反复听写、反复纠错,耗费大量时间精力&a…

作者头像 李华
网站建设 2026/5/25 3:06:42

C++ STL 容器详解:vector、list、map 与迭代器完全指南

目录 前言 一、STL 六大组件回顾 二、vector 容器详解 三、迭代器分类 四、list 容器详解 五、map 容器详解 六、总结 前言 STL 是 C 开发的核心利器,几乎所有项目都会用到容器、迭代器与算法。相比于 C 语言手动实现顺序表、链表、哈希结构,STL …

作者头像 李华
网站建设 2026/5/25 3:05:59

昇腾CANN ge 仓的图优化 Pass:哪些 Pass 真正影响推理性能

前言 你训练好一个模型,导出 ONNX,转成 CANN 的 OM 模型。推理时发现:延迟 89ms,吞吐只有 1200 samples/s。 你开始调优: 加 --op_precision_modeforce_fp16 → 延迟 72ms(快 19%)加 --auto_tun…

作者头像 李华
网站建设 2026/5/25 2:57:20

昇腾NPU强化学习训练实战——从PPO到GRPO的完整落地

强化学习(RL)在昇腾NPU上训练比监督学习复杂得多。你需要同时跑策略网络、价值网络,维护动态的经验回放缓冲区,还要处理动态Shape和显存碎片化问题。 这篇将手把手教你如何在昇腾NPU上高效训练RL模型,涵盖PPO/GRPO算法…

作者头像 李华