温馨提示×

如何禁止ubuntu ssh密码登

小樊
76
2026-10-04 01:32:09
栏目: 智能运维

在 Ubuntu 上禁止 SSH 使用密码登录(只允许密钥登录),可按以下步骤操作:


一、确保已配置好 SSH 密钥登录(非常重要)

在禁用密码前,必须先确认你能用密钥登录,否则会被锁在外面。

1. 生成密钥(本地机器)

ssh-keygen -t ed25519

2. 拷贝公钥到服务器

ssh-copy-id user@server_ip

3. 测试密钥登录

ssh user@server_ip

✅ 能登录再继续


二、修改 SSH 配置文件

编辑配置文件:

sudo nano /etc/ssh/sshd_config

找到并修改以下参数(没有就添加):

PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
UsePAM no

⚠️ 注意:

  • UsePAM no 在某些系统可能导致问题,推荐保持 UsePAM yes
  • 更安全的做法是只改:
PasswordAuthentication no

三、重启 SSH 服务

sudo systemctl restart ssh

(旧版本可能是 sshd)


四、(可选)禁止 root 密码登录

PermitRootLogin prohibit-password

五、验证

重新开一个终端测试:

ssh user@server_ip
  • 有密钥 → 可登录
  • 无密钥 → 直接拒绝

六、应急方案(防止被锁)

建议保留一个临时会话不要断开,或启用:

Match User tempuser
    PasswordAuthentication yes

如果你需要 只允许特定用户 / IP / 端口 的 SSH 配置,也可以告诉我。

0 踩