核心是确保公钥能被正确识别并关闭所有口令类验证通道:先生成ed25519密钥对、用ssh-copy-id上传公钥并严格设置~/.ssh权限为700、authorized_keys为600;再修改sshd_config启用PubkeyAuthentication yes、禁用PasswordAuthentication no和ChallengeResponseAuthentication no,最后重启sshd服务验证。

要让 SSH 完全依赖密钥认证、彻底禁用口令登录,核心是两步:确保公钥能被正确识别,同时关闭所有口令类验证通道。操作前务必确认密钥已成功登录过一次,否则可能锁死连接。
一、客户端生成并上传公钥
在本地机器运行:
-
ssh-keygen -t ed25519 -C "your_email@example.com"(推荐 ed25519,比 RSA 更快更安全;如需兼容旧系统可选
-t rsa -b 4096) - 按提示保存,默认路径
~/.ssh/id_ed25519(私钥)和~/.ssh/id_ed25519.pub(公钥) - 用 ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server_ip 自动上传公钥并设置权限;若不可用,手动执行:
cat ~/.ssh/id_ed25519.pub | ssh user@server_ip "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
二、服务端启用并锁定密钥认证
登录服务器,编辑 SSH 配置:
- 运行 sudo nano /etc/ssh/sshd_config(或 vim)
- 确认以下行存在且未被注释,值严格匹配:
RSAAuthentication yes(仅当使用 RSA 密钥时需开启)
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
ChallengeResponseAuthentication no
PermitRootLogin prohibit-password(允许 root 用密钥登录,但禁止密码)
AllowUsers your_username(可选,显式放行用户,提升可控性)
特别注意:PasswordAuthentication no 必须生效,且不能与 PermitRootLogin yes 共存——后者会重新打开 root 密码入口。
三、验证与重启
完成配置后:
- 先在另一终端窗口测试新密钥能否登录(不要关闭当前会话)
- 确认无误后执行:sudo systemctl restart sshd(Ubuntu/Debian/CentOS 7+)或 sudo service sshd restart(CentOS 6)
- 重启后,原密码登录方式将立即失效;root 用户若设为
prohibit-password,仍可通过密钥登录
整个过程不复杂但容易忽略权限和顺序——authorized_keys 文件权限必须是 600,.ssh 目录必须是 700,且配置修改后一定要重启服务才生效。

















