Linux服务器配置Google Authenticator需四步闭环:安装PAM模块、用户独立生成600权限密钥文件、在/etc/pam.d/sshd顶部添加auth [success=ok default=die]规则、启用sshd的ChallengeResponseAuthentication和UsePAM并重启服务。

在 Linux 服务器上配置 Google Authenticator 动态验证码实现多因素认证,核心是让 SSH 登录同时验证“静态凭证(密码或密钥)+ 时间动态口令(TOTP)”。这不是装个 App 就行,而是一套需四步闭环的系统集成:安装模块、用户初始化、PAM 规则注入、SSH 行为接管。整个过程不改动原有登录方式,只是在密码/密钥之后多加一次交互式输入。
安装 PAM 模块并确认路径有效
模块必须正确安装到系统安全模块目录,否则后续所有配置静默失效。
- Ubuntu/Debian:sudo apt update && sudo apt install libpam-google-authenticator -y,验证文件是否存在:ls /lib/security/pam_google_authenticator.so
- RHEL/CentOS 7:sudo yum install epel-release google-authenticator -y,检查:ls /usr/lib64/security/pam_google_authenticator.so
- RHEL/CentOS 8+ / Rocky / Alma:sudo dnf install epel-release google-authenticator -y
- 安装后务必运行 google-authenticator --version 确认命令可用;若提示 command not found,请检查 PATH 或重装
以目标用户身份生成密钥并保护文件权限
不能用 root 替代操作,每个用户必须独立生成自己的 ~/.google_authenticator 文件,且权限必须为 600(即 -rw-------)。
- 切换用户:su - username(推荐带 - 保证环境干净)
- 运行:google-authenticator,按提示选择:
- Do you want time-based tokens? → y(必须启用 TOTP)
- Disallow multiple uses? → y(防重放攻击)
- Increase time window? → n(保持默认 ±30 秒容差,扩展窗口会降低安全性)
- Enable rate-limiting? → y(默认 3 次/30 秒,防暴力尝试)
- Generate emergency scratch codes? → y(保存好这 5–10 个离线备用码,每用一个即作废)
- 扫描终端显示的二维码,或手动输入密钥到 Google/Microsoft/Authy 等支持 TOTP 的 App 中
- 执行 ls -l ~/.google_authenticator,确保输出含 -rw-------;若不是,立即修复:chmod 600 ~/.google_authenticator
精准配置 PAM 规则,控制验证时机与逻辑
/etc/pam.d/sshd 是关键入口,添加位置和控制语法决定是否生效、是否可绕过、失败时是否锁死全部登录。
- 编辑:sudo nano /etc/pam.d/sshd
- 在文件最顶部插入一行(切勿放在 @include common-auth 后面): auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so nullok
- nullok 表示该用户尚未生成密钥时仍可登录(适合灰度上线);生产环境应改为: auth [success=ok default=die] pam_google_authenticator.so secret=/home/${USER}/.google_authenticator
- 绝对不要写 required 或 requisite ——一旦模块异常(如文件权限错、SELinux 拦截),会导致所有 SSH 登录被拒绝,无法远程恢复
调整 SSH 配置并重启服务
PAM 只负责“验什么”,SSH 才决定“要不要触发验”。缺这一步,TOTP 完全不会弹出。
- 编辑:sudo nano /etc/ssh/sshd_config
- 确保以下三项明确启用(取消注释并设为 yes):
- ChallengeResponseAuthentication yes
- UsePAM yes
- PasswordAuthentication yes(若用密钥登录,可设为 no,但须保留 PubkeyAuthentication yes)
- 可选增强(推荐):AuthenticationMethods publickey,keyboard-interactive(强制先验密钥,再输动态码)
- 重启服务:sudo systemctl restart sshd(Ubuntu/Debian/CentOS 8+)或 sudo service sshd restart(CentOS 7)


















