【Git】git使用SSH密钥实现身份验证
1. 生成 SSH 密钥对(公钥和私钥)。2. 将公钥添加到你的 Git 服务器账户中。3. 配置 Git 使用 SSH 协议来克隆和推送仓库。
·
Git 使用 SSH 协议进行安全通信,主要通过 SSH 密钥对实现身份验证。
1. 生成 SSH 密钥
在本地终端执行:
ssh-keygen -t ed25519 -C "your_email@example.com"
- 参数说明:
-t ed25519:推荐算法(或使用-t rsa -b 4096)-C:注释(通常用邮箱)
- 按提示操作:
- 保存路径:默认
~/.ssh/id_ed25519 - 设置密码(可选,增强安全性)
- 保存路径:默认
2. 添加公钥到 Git 平台
- 复制公钥:
cat ~/.ssh/id_ed25519.pub # 复制输出的内容 - 添加到平台:
- GitHub:
Settings → SSH and GPG keys → New SSH key - GitLab:
Preferences → SSH Keys - Gitee:
设置 → SSH 公钥
- GitHub:
3. 配置 Git 仓库使用 SSH
- 克隆仓库:
git clone git@github.com:user/repo.git # 使用 SSH 链接 - 修改现有仓库:
git remote set-url origin git@github.com:user/repo.git
4. 验证 SSH 连接
ssh -T git@github.com # GitHub
ssh -T git@gitlab.com # GitLab
成功提示:
Hi username! You've successfully authenticated...
5. 多账户配置
编辑 ~/.ssh/config 文件:
# 账户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_key
- 使用方式:
git clone git@github-work:company/project.git
6. 常见问题解决
- 权限错误:
chmod 700 ~/.ssh chmod 600 ~/.ssh/* - 连接超时:
- 检查防火墙或代理设置(如
~/.ssh/config添加ProxyCommand)。
- 检查防火墙或代理设置(如
- 密钥加载失败:
eval $(ssh-agent) # 启动代理 ssh-add ~/.ssh/your_key # 添加私钥
SSH vs HTTPS
| 特性 | SSH | HTTPS |
|---|---|---|
| 认证方式 | 密钥对 | 用户名/密码或个人访问令牌 |
| 端口 | 22 | 443 |
| 安全性 | 高(加密通道) | 高(SSL/TLS) |
| 多账户支持 | 方便(通过 config 文件) |
需缓存凭据 |
| 企业网络限制 | 可能被防火墙拦截 | 通常放行 |
更多推荐
所有评论(0)