配置 GitHub SSH 密钥
1. 为什么需要 SSH 密钥?
使用 HTTPS 克隆/推送代码时,每次都需要输入 GitHub 账号密码(或 Personal Access Token)。而 SSH(Secure Shell) 提供了一种更安全、更方便的认证方式:
- 免密码登录(配置后无需每次输入)
- 更高安全性(基于加密密钥对)
- 适合自动化流程(如 CI/CD)
本文将详细介绍如何生成并配置 SSH 密钥连接到 GitHub。
2. 检查现有 SSH 密钥
首先查看是否已有 SSH 密钥(默认存储在 ~/.ssh/
目录):
ls -al ~/.ssh
如果看到 id_rsa
和 id_rsa.pub
(或 id_ed25519
),说明已有密钥,可跳过生成步骤。
3. 生成新的 SSH 密钥
3.1 生成密钥对(推荐 Ed25519 算法)
ssh-keygen -t ed25519 -C "your_email@example.com"
- 按回车接受默认存储路径(
~/.ssh/id_ed25519
) - 输入密码(可选,增加安全性)
如果系统不支持 Ed25519,改用 RSA:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
3.2 查看公钥内容
cat ~/.ssh/id_ed25519.pub
输出类似:
ssh-ed25519 AAAAC3Nz... your_email@example.com
4. 将 SSH 密钥添加到 GitHub
- 登录 GitHub → Settings → SSH and GPG keys
- 点击 New SSH key
- 填写:
- Title:标识密钥用途(如
My Laptop
) - Key type:保持默认
Authentication Key
- Key:粘贴刚才复制的公钥内容(
id_ed25519.pub
)
- Title:标识密钥用途(如
- 点击 Add SSH key
5. 测试 SSH 连接
ssh -T git@github.com
如果看到:
Hi username! You've successfully authenticated...
说明配置成功!
6. 配置 Git 使用 SSH
6.1 修改现有仓库的远程地址
如果之前用的是 HTTPS,需切换为 SSH:
git remote set-url origin git@github.com:username/repo.git
检查是否生效:
git remote -v
# 应显示 ssh 地址(git@github.com:...)
### **6.2 克隆新仓库(使用 SSH)**
```bash
git clone git@github.com:username/repo.git
7. 常见问题解决
7.1 权限错误(Permissions too open)
如果遇到 WARNING: UNPROTECTED PRIVATE KEY FILE!
,修复密钥文件权限:
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
7.2 SSH 代理管理
如果设置了密钥密码,每次使用需输入,可通过 ssh-agent
管理:
# 启动代理
eval "$(ssh-agent -s)"
# 添加密钥
ssh-add ~/.ssh/id_ed25519
7.3 多账号配置
如果需要为不同 GitHub 账号配置不同密钥,创建 ~/.ssh/config
文件:
# 默认账号
Host github.com
HostName github.com
IdentityFile ~/.ssh/id_ed25519
# 工作账号
Host github-work
HostName github.com
IdentityFile ~/.ssh/work_key
然后克隆时使用别名:
git clone git@github-work:company/repo.git
8. 最佳实践
- 定期更换密钥(建议每年一次)
- 不要共享私钥(
id_ed25519
文件等同密码) - 使用强密码保护密钥
- 启用 GitHub 2FA(双因素认证)
9. 总结
通过 SSH 连接 GitHub 只需 3 步:
- 生成密钥对:
ssh-keygen -t ed25519
- 添加公钥到 GitHub:粘贴
~/.ssh/id_ed25519.pub
- 测试连接:
ssh -T git@github.com
配置完成后,你将享受更安全、更便捷的 Git 操作体验!
扩展阅读:
- GitHub SSH 文档
- SSH 密钥类型对比