在 Ubuntu 上禁止 SSH 使用密码登录(只允许密钥登录),可按以下步骤操作:
在禁用密码前,必须先确认你能用密钥登录,否则会被锁在外面。
ssh-keygen -t ed25519
ssh-copy-id user@server_ip
ssh user@server_ip
✅ 能登录再继续
编辑配置文件:
sudo nano /etc/ssh/sshd_config
找到并修改以下参数(没有就添加):
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
UsePAM no
⚠️ 注意:
UsePAM no 在某些系统可能导致问题,推荐保持 UsePAM yesPasswordAuthentication no
sudo systemctl restart ssh
(旧版本可能是 sshd)
PermitRootLogin prohibit-password
重新开一个终端测试:
ssh user@server_ip
建议保留一个临时会话不要断开,或启用:
Match User tempuser
PasswordAuthentication yes
如果你需要 只允许特定用户 / IP / 端口 的 SSH 配置,也可以告诉我。