本文目标:让 SSH 进入“root 仅密钥可登录,密码彻底禁用”状态。
⚠️ 建议保留一条已登录会话/控制台,避免误配置锁门。
✅ 最终效果
- 只允许公钥:
PubkeyAuthentication yes - 禁用密码:
PasswordAuthentication no - root 仅密钥:
PermitRootLogin prohibit-password
🔧 1. 确认 SSH 服务已安装并运行
apt update
apt install -y openssh-server
systemctl enable --now ssh
🔑 2. 本地生成密钥(已存在可跳过)
Linux / macOS:
ssh-keygen -t ed25519 -a 64 -C "root@debian" -f ~/.ssh/id_ed25519
Windows(PowerShell):
ssh-keygen -t ed25519 -a 64 -C "root@debian" -f $env:USERPROFILE\.ssh\id_ed25519
📌 3. 把公钥写入 root 的 authorized_keys
如果你此刻能用 root 登录(比如初始密码/控制台),直接用 ssh-copy-id:
ssh-copy-id -i ~/.ssh/id_ed25519.pub root@<服务器IP>
Windows(PowerShell)可用下面这条等价命令:
Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub | ssh root@<服务器IP> "umask 077; mkdir -p /root/.ssh; cat >> /root/.ssh/authorized_keys"
不方便 ssh-copy-id 就手工写(在服务器上执行):
mkdir -p /root/.ssh
chmod 700 /root/.ssh
nano /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
💡
authorized_keys每行一把公钥,把id_ed25519.pub内容粘进去即可。
🔒 4. 配置 SSH:允许 root,但只准密钥;禁用密码
推荐用分片配置(更干净、好回滚):
nano /etc/ssh/sshd_config.d/10-key-only.conf
写入:
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin prohibit-password
PermitEmptyPasswords no
🧪 5. 自检并重载
sshd -t
systemctl reload ssh
✅ 6. 验证
ssh -i ~/.ssh/id_ed25519 root@<服务器IP>
(可选)强制走密码应当失败:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no root@<服务器IP>
🛠️ 回滚(进不去时)
用控制台登录后删除分片配置并重启:
rm -f /etc/ssh/sshd_config.d/10-key-only.conf
sshd -t
systemctl restart ssh