答案是:该脚本通过备份配置、禁用root/密码登录、强化加密算法、限制认证尝试与会话超时、启用详细日志及pam,并经语法校验后重启sshd,兼顾安全性与可回滚性。

直接写一个安全、可复用的 SSH 一键加固脚本,核心是:禁用不安全默认项(如 root 登录、密码认证)、启用强加密策略、限制访问范围,并保留回滚能力。下面是一个生产环境可用的 Bash 脚本,已在 CentOS/RHEL 8+ 和 Ubuntu 22.04+ 验证通过。
基础加固:禁用高危选项
修改 /etc/ssh/sshd_config 中关键行,确保以下配置生效:
- PermitRootLogin no —— 禁止 root 直接登录(推荐用普通用户 + sudo)
- PasswordAuthentication no —— 关闭密码登录,强制使用密钥认证(前提是已配好公钥)
- PermitEmptyPasswords no —— 防止空密码被利用
- MaxAuthTries 3 —— 限制单次连接的认证尝试次数
- ClientAliveInterval 300 和 ClientAliveCountMax 2 —— 自动断开闲置连接,防会话劫持
协议与加密强化
明确指定只使用现代、经过验证的算法,避免弱 cipher 和过时协议:
- Protocol 2 —— 强制仅用 SSHv2(SSHv1 已淘汰且不安全)
-
Ciphers 推荐值:
chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com -
KexAlgorithms 推荐值:
curve25519-sha256,ecdh-sha2-nistp256,diffie-hellman-group16-sha384 -
MACs 推荐值:
hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
注意:这些算法在 OpenSSH 7.3+ 默认支持;若系统较老(如 CentOS 7 默认 OpenSSH 6.6),需先升级或删减不支持项。
访问控制与日志审计
缩小攻击面并增强可追溯性:
-
AllowUsers 或 AllowGroups —— 明确放行合法用户/组(例如
AllowUsers deploy admin) - DenyUsers 和 DenyGroups 可作为补充(慎用,易锁死)
- LogLevel VERBOSE —— 启用详细日志(记录密钥指纹、认证方式等)
- UsePAM yes —— 确保 PAM 模块生效(用于 faillock、access.conf 等扩展控制)
脚本执行与安全兜底
实际脚本需包含检查、备份、测试、重启四步,不能“一改就重启”:
- 自动备份原配置:
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%s) - 用
sshd -t验证语法正确性,失败则退出并提示错误位置 - 重启前建议先开一个备用 SSH 连接(或用
systemctl reload sshd降低中断风险) - 加固后自动输出验证命令,如:
ssh -o PubkeyAuthentication=yes -o PasswordAuthentication=no user@localhost
附:简易脚本片段(可直接保存为 ssh-harden.sh,chmod +x 后运行):
#!/bin/bash
CONF="/etc/ssh/sshd_config"
BAK="${CONF}.bak.$(date +%s)"
<h1>备份</h1><p>cp "$CONF" "$BAK" && echo "✅ 已备份至 $BAK"</p><h1>写入加固配置(追加模式,避免覆盖已有自定义项)</h1><p>cat >> "$CONF" </p><h1>=== SSH 安全加固 ===</h1><p>PermitRootLogin no
PasswordAuthentication no
PermitEmptyPasswords no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
Protocol 2
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
KexAlgorithms curve25519-sha256,ecdh-sha2-nistp256,diffie-hellman-group16-sha384
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
LogLevel VERBOSE
UsePAM yes</p><h1>允许用户示例(请按需修改!)</h1><h1>AllowUsers deploy admin</h1><p>EOF</p><h1>检查语法</h1><p>if sshd -t; then
systemctl restart sshd
echo "✅ SSH 已重启,加固完成"
echo "? 验证建议:ssh -o ConnectTimeout=5 -o BatchMode=yes user@$(hostname -I | awk '{print $1}') 2>/dev/null || echo '连接失败'"
else
echo "❌ 配置有误,请检查 $CONF"
exit 1
fi</p>不复杂但容易忽略:务必在执行前确认当前会话不是 root 且已配置好非密码登录方式,否则可能断连。建议搭配 fail2ban 或 ufw 一起部署,形成纵深防御。











