温馨提示×

怎样配置Ubuntu SSH密钥

小樊
40
2026-08-23 00:37:59
栏目: 智能运维

在 Ubuntu 上配置 SSH 密钥(公钥 / 私钥) 一般用于 无密码登录服务器Git(GitHub / GitLab)。下面我按最常见场景一步一步说明。


一、在本地 Ubuntu 生成 SSH 密钥

1️⃣ 打开终端

2️⃣ 生成密钥

ssh-keygen -t ed25519 -C "your_email@example.com"

推荐ed25519(更安全、更快)
如果你的系统较老,也可以用:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

3️⃣ 提示说明

Enter file in which to save the key (/home/user/.ssh/id_ed25519):
  • 直接 回车(默认即可)
  • 或自定义路径,如:/home/user/.ssh/github_key
Enter passphrase (empty for no passphrase):
  • 建议设置一个密码(更安全)
  • 不想输密码可直接回车

二、查看生成的密钥

ls ~/.ssh

你会看到类似:

id_ed25519      # 私钥(⚠️ 不能泄露)
id_ed25519.pub  # 公钥(可以放到服务器 / Git 网站)

查看公钥内容:

cat ~/.ssh/id_ed25519.pub

三、配置到远程服务器(SSH 登录)

方法一:自动复制(推荐)

ssh-copy-id user@server_ip

示例:

ssh-copy-id root@192.168.1.100

输入一次服务器密码即可

方法二:手动复制

  1. 复制本地公钥内容
cat ~/.ssh/id_ed25519.pub
  1. 登录服务器
ssh user@server_ip
  1. 在服务器执行:
mkdir -p ~/.ssh
nano ~/.ssh/authorized_keys
  1. 粘贴公钥内容并保存

  2. 设置权限:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

四、配置 SSH 客户端(可选但推荐)

编辑:

nano ~/.ssh/config

示例配置:

Host myserver
    HostName 192.168.1.100
    User root
    IdentityFile ~/.ssh/id_ed25519

以后直接:

ssh myserver

五、禁用密码登录(增强安全)

⚠️ 先确保 SSH 密钥能正常登录

在服务器编辑:

sudo nano /etc/ssh/sshd_config

修改或确认:

PasswordAuthentication no
PubkeyAuthentication yes

重启 SSH:

sudo systemctl restart ssh

六、用于 GitHub / GitLab(可选)

  1. 复制公钥
cat ~/.ssh/id_ed25519.pub
  1. 添加到:
  • GitHub:
    Settings → SSH and GPG keys → New SSH key
  • GitLab:
    Preferences → SSH Keys
  1. 测试:
ssh -T git@github.com

七、常见问题

❌ 权限错误

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

❌ SSH 仍然要求密码

  • 检查 authorized_keys
  • 检查 sshd_config
  • 查看日志:
sudo tail -f /var/log/auth.log

如果你愿意,可以告诉我: ✅ 是 本地 Ubuntu → 服务器
✅ 还是 GitHub / GitLab
✅ 或 Windows + Ubuntu 双系统 / WSL

我可以按你的具体环境提供更精准的配置方案。

0