Git SSH 配置详细教程
配置 Git SSH 密钥的步骤如下,适用于 GitHub、GitLab 等平台:
一、生成 SSH 密钥
打开终端(Windows:Git Bash / CMD;Mac/Linux:Terminal)
生成密钥(替换邮箱):
1
ssh-keygen -t ed25519 -C "your_email@example.com"
- 提示保存位置:按
Enter
使用默认路径~/.ssh/id_ed25519
- 设置密码(可选):为密钥增加额外保护
💡 如果系统不支持 Ed25519,改用 RSA:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
- 提示保存位置:按
二、将公钥添加到 Git 平台
- 复制公钥内容:
1
2
3
4
5
6
7# macOS/Linux
cat ~/.ssh/id_ed25519.pub | pbcopy
# Windows (Git Bash)
cat ~/.ssh/id_ed25519.pub | clip
# 或手动打开文件复制 - 添加到平台:
- GitHub:Settings → SSH and GPG keys → New SSH key
- GitLab:Preferences → SSH Keys
- 其他平台:在用户设置中找到 SSH 密钥管理
三、配置 SSH 代理(推荐)
1 | # 启动 ssh-agent |
四、测试连接
1 | ssh -T git@github.com # 测试 GitHub |
成功响应示例:Hi username! You've successfully authenticated...
五、配置 Git 使用 SSH
克隆仓库时使用 SSH URL:
1 | git clone git@github.com:username/repo.git |
如果之前使用 HTTPS,可修改远程 URL:
1 git remote set-url origin git@github.com:username/repo.git
常见问题解决
- 权限错误:
1
2chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519* - 连接被拒绝:
- 检查网络是否允许 SSH(端口 22)
- 平台是否支持 Ed25519(老旧系统建议用 RSA)
- 多账号管理:
在~/.ssh/config
中配置多账号:使用:1
2
3
4
5
6
7
8
9
10
11# 账号1 (默认)
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
# 账号2
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/work_keygit clone git@github-work:company/project.git
验证配置
1 | ssh -vT git@github.com # 查看详细连接过程 |
完成以上步骤后,即可免密码安全使用 Git 操作。遇到问题可检查 ~/.ssh/known_hosts
文件或更新平台公钥。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 九毫的自留地!
评论