首页 > 服务器    日期:2026-07-05 / 浏览

Ubuntu SSH 强制密钥登录:配置不生效的排查与修复

症状
修改 PasswordAuthentication yes 并重启 sshd,客户端仍报 Permission denied (publickey)

根因
sshd 运行时配置由多个文件合并决定,云镜像默认配置往往被 /etc/ssh/sshd_config.d/50-cloud-init.conf 中的 PasswordAuthentication no 覆盖,或存在 AuthenticationMethods 限制。

排查步骤

1. 查看 sshd 运行时生效值

sudo sshd -T | grep -E 'passwordauthentication|authenticationmethods|kbdinteractiveauthentication'

要求:

  • passwordauthentication yes
  • authenticationmethods 输出为空(无任何限制)
  • kbdinteractiveauthentication yes

任何一项不符,继续。

2. 定位冲突配置文件

sudo grep -rn "PasswordAuthentication\|AuthenticationMethods" /etc/ssh/sshd_config /etc/ssh/sshd_config.d/

常见冲突源:/etc/ssh/sshd_config.d/50-cloud-init.conf 内含 PasswordAuthentication no

3. 创建高优先级覆盖配置

sudo tee /etc/ssh/sshd_config.d/99-password-auth.conf <<EOF
PasswordAuthentication yes
KbdInteractiveAuthentication yes
EOF

若步骤 1 中发现 authenticationmethods 非空,追加一行以清空限制:

echo "AuthenticationMethods password" | sudo tee -a /etc/ssh/sshd_config.d/99-password-auth.conf

4. 语法检查并重启服务

sudo sshd -t && sudo systemctl restart ssh

5. 确认用户密码可用

sudo passwd -S <username>

状态必须为 P(密码已设置)。若为 L(锁定),执行 sudo passwd -u <username>;若为 NP(无密码),执行 sudo passwd <username>

6. 验证客户端支持的认证方式

ssh -o PreferredAuthentications=password -v user@host

输出中应出现 Authentications that can continue: password

常见错误与处理

AuthenticationMethods publickey 强制密钥
→ 在步骤 3 覆盖为 AuthenticationMethods password 或直接注释原文件行。

KbdInteractiveAuthentication no 导致 PAM 密码认证失效
→ 步骤 3 已覆盖。

用户密码未设置或锁定
→ 步骤 5 解决。

sshd -T 仍显示 passwordauthentication no
→ 检查 /etc/ssh/sshd_config.d/ 下文件名的排序,确保 99- 文件最晚加载。可用 sudo sshd -T | grep -B1 passwordauthentication 观察来源文件(需 root 权限查看)。

恢复密钥认证(运维后必做)

sudo rm /etc/ssh/sshd_config.d/99-password-auth.conf
sudo systemctl restart ssh

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章