运行 google-authenticator 命令可生成 TOTP 密钥并写入 ~/.google_authenticator 文件,需普通用户执行、安装对应 PAM 包、正确设置文件权限为 600,并按提示选择 y 启用时间令牌、更新文件、防重放、限速等关键选项。

直接运行 google-authenticator 命令即可生成密钥,它会自动写入当前用户的 ~/.google_authenticator 文件,并输出密钥、二维码 URL 和恢复码。
运行 google-authenticator 前必须确保用户已安装对应 PAM 包
不同发行版安装命令不同,但核心是让 google-authenticator 可执行命令存在:
- Ubuntu/Debian:
sudo apt install libpam-google-authenticator - CentOS/RHEL 8+:
sudo dnf install google-authenticator(需先启用 EPEL) - CentOS 7:
sudo yum install epel-release && sudo yum install google-authenticator
注意:该命令**不支持 root 用户直接运行生成有效密钥用于 SSH 登录**(PAM 配置默认跳过 root),应切换到普通用户(如 sudo -u username google-authenticator)或用目标用户登录后执行。
google-authenticator 交互选项直接影响密钥行为和安全性
首次运行会逐项提问,选错可能导致验证失败或时间偏移容忍度过高:
-
Do you want authentication tokens to be time-based?→ 必须选y(TOTP 模式,手机端通用) -
Do you want me to update your "~/.google_authenticator" file?→ 选y,否则密钥不落地 -
Do you want to disallow multiple uses of the same authentication token?→ 选y,防止重放攻击 -
By default, tokens are good for 30 seconds.→ 一般选n;仅当服务器与手机时间差 > 1 分钟才考虑y(会放宽窗口至 60 秒) -
Enable rate-limiting?→ 推荐y,防暴力尝试(30 秒内最多 3 次失败)
执行完成后,终端会显示类似这样的关键信息:
Access Gmail, Calendar, Drive, Docs, and Sheets via the gws CLI or Python.
Your new secret key is: WKDPJHOKR2P3DOWL Your verification code is 189192 Your emergency scratch codes are: 77678926 14729443 ...
WKDPJHOKR2P3DOWL 就是你要手动输入到 Google Authenticator / Microsoft Authenticator 等 App 中的密钥(非扫描时用)。
没装 qrencode 也能拿到二维码,但形式不同
如果系统未安装 qrencode(如 minimal CentOS 安装),google-authenticator 不会渲染终端二维码,而是输出一个形如:
https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/username@hostname%3Fsecret%3DWKDPJHOKR2P3DOWL%26issuer%3Dhostname
把这个 URL 复制进手机浏览器,就能看到可扫描的二维码。别手输 —— 密钥含大小写字母+数字共 16 位,极易出错。
密钥一旦生成,~/.google_authenticator 文件权限必须为 600(chmod 600 ~/.google_authenticator),否则 PAM 拒绝读取 —— 这是最常被忽略、导致“配置好了却始终提示验证码错误”的硬性条件。

















