温馨提示×

ubuntu ssh密钥怎么配置

小樊
46
2026-09-19 04:33:38
栏目: 智能运维

在 Ubuntu 上配置 SSH 密钥(用于免密登录远程服务器)一般分为本地生成密钥把公钥放到服务器两步。下面是最常用的做法:


一、在本地 Ubuntu 生成 SSH 密钥

  1. 打开终端,执行:
ssh-keygen -t rsa -b 4096

或(更推荐,现代系统):

ssh-keygen -t ed25519
  1. 会提示:
Enter file in which to save the key (/home/用户名/.ssh/id_ed25519):
  • 直接回车使用默认路径即可
  1. 设置密码(可选):
Enter passphrase (empty for no passphrase):
  • 不想每次输入密码就直接回车

生成后你会看到:

~/.ssh/id_ed25519        # 私钥(不能泄露)
~/.ssh/id_ed25519.pub    # 公钥(可发给服务器)

二、把公钥复制到远程服务器

方法 1(最简单,推荐)

ssh-copy-id 用户名@服务器IP

例如:

ssh-copy-id ubuntu@192.168.1.100

输入一次服务器密码后,以后就可以免密登录。


方法 2(手动复制)

如果没法用 ssh-copy-id

  1. 查看公钥内容:
cat ~/.ssh/id_ed25519.pub
  1. 登录服务器,把内容追加到:
~/.ssh/authorized_keys
  1. 设置权限:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

三、测试 SSH 登录

ssh 用户名@服务器IP

如果不再提示输入密码,说明配置成功 ✅


四、常见问题

1. 权限错误导致登录失败

本地也要保证权限正确:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519

2. 服务器未开启密钥登录

编辑服务器上的:

sudo vim /etc/ssh/sshd_config

确保有:

PubkeyAuthentication yes

然后重启:

sudo systemctl restart ssh

3. 禁用密码登录(更安全)

确认密钥可用后,可设置:

PasswordAuthentication no

如果你是想:

  • 配置 GitHub / GitLab SSH
  • 配置 多台服务器不同密钥
  • Windows + Ubuntu 混合环境

可以告诉我具体场景,我可以给你更针对性的配置方式。

0