ssh登录不提示输入验证码,根本原因是验证流程被跳过:未启用usepam yes、pam规则位置错误(如加在@include common-auth之后)、用户密钥文件权限非600、或客户端未启用keyboard-interactive认证。

直接配 google-authenticator 不行,必须同时改 PAM 规则、SSH 配置、用户密钥文件权限,三者缺一不可。只装模块或只开 ChallengeResponseAuthentication,登录时根本不会让你输验证码。
为什么 SSH 登录不提示输入验证码?
这是最常遇到的问题,现象是:输密码就直接进去了,或者报 Permission denied (publickey) 却没看到验证码输入提示。根本原因不是模块没装,而是验证流程被跳过:
-
UsePAM yes没开 —— SSH 根本不调用 PAM,/etc/pam.d/sshd所有配置都无效 -
PubkeyAuthentication yes且用户有公钥,OpenSSH 默认优先走公钥认证,绕过 PAM 的验证码环节 - PAM 规则加在了错误位置,比如写在
@include common-auth后面,导致密码验证成功后流程终止,不再执行后续模块 - 客户端没启用键盘交互,OpenSSH 8.2+ 默认禁用
keyboard-interactive,需显式指定
验证是否触发 PAM:用另一台机器测试时加 -o PreferredAuthentications=keyboard-interactive,例如:ssh -o PreferredAuthentications=keyboard-interactive user@host。
/etc/pam.d/sshd 中 auth 行怎么写才有效?
不能简单写 auth required pam_google_authenticator.so,也不要用 [success=done default=ignore] 这类易绕过的控制标志。正确写法取决于你希望的认证逻辑:
Linux 性能分析与调优专家,覆盖 CPU、内存、磁盘 I/O、网络、内核参数、编译优化、容器/K8s。适用场景:系统卡顿/高负载、内存不足/OOM/Swap 高、CPU 异常/iowait 高。
- 强制所有用户双因子(推荐上线前):
auth [success=ok default=die] pam_google_authenticator.so secret=/home/${USER}/.google_authenticator - 允许未配置 MFA 的用户降级为单因子(仅调试用):
auth [success=ok default=ignore] pam_google_authenticator.so nullok,但上线前必须删掉nullok - 务必加在
@include common-auth之前,否则密码验证先通过,流程结束 - 不要用
requisite类型,它失败会直接中断整个 auth 流程,导致连密码都输不了
检查路径:Debian/Ubuntu 是 /lib/security/pam_google_authenticator.so,RHEL/CentOS 是 /usr/lib64/security/pam_google_authenticator.so,路径错会导致 PAM 加载失败且无日志提示。
google-authenticator 命令哪些选项不能乱选?
运行 google-authenticator 时,5 个问题里有 3 个直接影响可用性和安全性,不是全按 y 就完事:
- “Do you want authentication tokens to be time-based?” → 必须选
y,否则不是 TOTP,手机 App 无法同步 - “Do you want to disallow multiple uses of the same authentication token?” → 必须选
y,否则同一验证码可重复使用,失去防重放意义 - “By default, tokens are good for 30 seconds” → 不要改这个值,客户端和服务端时间偏差超过 ±30 秒就会失败;与其调窗口,不如用
chronyd或ntpdate同步时间 - 生成的
~/.google_authenticator文件权限必须是600(-rw-------),且所在目录属主必须是该用户,否则 PAM 静默拒绝读取 - 应急码(scratch codes)一定要离线保存,一旦手机丢失或重装 App,这是唯一恢复入口
配置后测试失败,该看哪条日志?
别只盯着 ssh 连接结果,真正关键的日志在 /var/log/auth.log(Debian/Ubuntu)或 /var/log/secure(RHEL/CentOS)。常见线索:
- 出现
pam_google_authenticator: Couldn't open /home/user/.google_authenticator: Permission denied→ 权限或属主不对 - 出现
pam_google_authenticator: Invalid verification code→ 时间不同步,或手机 App 未正确绑定密钥 - 完全没出现
pam_google_authenticator相关日志 → SSH 没调用 PAM,检查UsePAM yes和sshd -T | grep usepam - 出现
error: maximum authentication attempts exceeded→ 输错太多次被 PAM 锁定,需等冷却或手动清理/var/run/nologin类文件
最易被忽略的是时间同步和 PAM 规则顺序——这两点出问题,其他所有操作都白做。










