PermitRootLogin prohibit-password是唯一正解:允许root密钥登录、禁止密码认证,但必须协同PasswordAuthentication no、PubkeyAuthentication yes及authorized_keys权限600等条件才生效。

PermitRootLogin prohibit-password 是唯一正解
想只禁密码、留密钥,PermitRootLogin prohibit-password 是 sshd 唯一支持的语义。设成这个值后,SSH 守护进程会在认证阶段主动拒绝所有密码类认证方式(包括 PasswordAuthentication 和 KbdInteractiveAuthentication),但允许 PubkeyAuthentication 成功时放行 root。它不是“半开”,而是协议层明确区分认证类型的结果。
常见错误是只改这一项,却没同步收紧其他参数:
-
PasswordAuthentication yes仍开着 → 攻击者可通过其他用户爆破后su -切 root,绕过限制 -
PubkeyAuthentication no或AuthorizedKeysFile路径错 → root 密钥登录直接失败,等于锁死自己 -
/root/.ssh/authorized_keys权限不是600或属主不对 → OpenSSH 拒绝读取,报Authentication refused: bad ownership or modes
必须关闭 PasswordAuthentication 才算真正生效
PermitRootLogin prohibit-password 单独存在时毫无意义——它只告诉 sshd “如果 root 来了,别收密码”。但只要 PasswordAuthentication yes 还开着,任何用户(包括非 root)都能用密码登录,再通过 sudo su - 或 su - 提权,等同于变相开放 root 权限。
所以真实生效链条是:攻击者无法用 ssh root@host 密码登录 → 也无法用 ssh alice@host 密码登录 → 只能靠预置密钥接入指定用户 → 再经 sudo 审计提权。这三步缺一不可。
- 编辑
/etc/ssh/sshd_config,确认两行同时存在且未注释:PermitRootLogin prohibit-passwordPasswordAuthentication no - 重启服务前,务必用新终端测试:
ssh -o PubkeyAuthentication=yes -o PasswordAuthentication=no root@localhost应成功;加-o PasswordAuthentication=yes应立刻失败 - 云服务器建议先开 VNC 控制台,防止密钥部署失误导致失联
AllowUsers 比 PermitRootLogin 更早拦截连接
如果你的目标是“连登录提示都不给”,AllowUsers 比 PermitRootLogin 更底层。它在用户认证前就做白名单匹配,不匹配的连接连 password: 提示都不会出现,日志里只记 Connection closed by authenticating user。
但写错就会全拒,必须严格检查:
-
AllowUsers值必须是已存在的普通用户名,不能含root,多个用空格分隔,例如:AllowUsers deploy admin - 对应用户的
~/.ssh/authorized_keys必须存在且权限为600,家目录需为755,否则密钥认证失败 - 不要和
DenyUsers混用——AllowUsers优先级更高,DenyUsers root在它面前无效
禁止密码登录后,密钥部署最容易被忽略的细节
关掉密码登录不等于安全,只是把入口从“密码”换成了“密钥”。而密钥失效往往不是配置错,而是文件权限或路径问题。
验证 root 密钥是否真能用,别只信 ssh-copy-id 的返回:
- 手动检查
/root/.ssh/authorized_keys文件权限:ls -l /root/.ssh/authorized_keys输出应为-rw-------,属主为root - 确认
/root/.ssh目录权限是700,否则 OpenSSH 拒绝加载任何密钥 -
AuthorizedKeysFile默认是.ssh/authorized_keys,但如果自定义过路径(如AuthorizedKeysFile /etc/ssh/keys/%u),必须确保该路径下有 root 的公钥文件且权限正确 - 测试命令加
-v参数:ssh -v -o PubkeyAuthentication=yes root@host,看日志里是否出现Offering public key和Server accepts key
实际操作中,最常卡住的不是改哪行配置,而是改完之后没在新终端里跑一次真实连接测试,就直接关掉了当前 root 会话。一旦密钥没配好,连控制台都进不去。











