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

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


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

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


排查步骤

1. 查看 sshd 运行时生效值

sudosshd-T|grep-E'passwordauthentication|authenticationmethods|kbdinteractiveauthentication'

要求:

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

任何一项不符,继续。

2. 定位冲突配置文件

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

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

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

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

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

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

4. 语法检查并重启服务

sudosshd-t&&sudosystemctl restartssh

5. 确认用户密码可用

sudopasswd-S<username>

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

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

ssh-oPreferredAuthentications=password-vuser@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 权限查看)。


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

sudorm/etc/ssh/sshd_config.d/99-password-auth.confsudosystemctl restartssh