Git 配置 SSH 连接 GitHub

Git 配置 SSH 连接 GitHub

1. 生成 SSH 密钥

使用 ssh-keygen 命令生成一对密钥,推荐使用 Ed25519 算法:

ssh-keygen -t ed25519 -C "你的GitHub邮箱" -f ~/.ssh/github_id_ed25519

也可以使用 RSA 算法:

ssh-keygen -t rsa -b 4096 -C "你的GitHub邮箱" -f ~/.ssh/github_id_rsa

参数说明:

  • -t:指定密钥算法。
  • -b:指定密钥位数,Ed25519 算法没有这个参数。
  • -C:为密钥添加注释,通常是邮箱。
  • -f:指定密钥的存放位置及名称。 ~/.ssh/ 是默认目录,推荐存放于此。

2. 查看公钥

把公钥内容复制出来:

cat ~/.ssh/github_id_ed25519.pub

复制输出的整段内容。

3. 添加公钥到 GitHub

进入 GitHub 的 SSH keys 配置页面,粘贴刚才复制的公钥并保存。

4. 编辑 SSH 的配置文件

编辑 SSH 的配置文件 ~/.ssh/config ,添加:

Host github.com
  HostName ssh.github.com
  Port 22
  User git
  IdentityFile ~/.ssh/github_id_ed25519

如果网络环境屏蔽了 22 端口,可以改用 443 端口。将 Port 改为 443

5. 测试 SSH 连接

执行:

ssh -T git@github.com

如果配置成功,会看到类似提示:

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

6. 修改仓库远程地址为 SSH

查看当前远程地址:

git remote -v

如果是 HTTPS,可以改成 SSH:

git remote set-url origin git@github.com:username/repo.git

Git 配置 SSH 连接 GitHub
https://blog.979909.xyz/2026/05/30/Git-配置-SSH-连接-GitHub/
作者
nafeuy
发布于
2026年5月30日
许可协议