Git Bash 关联已存在的 SSH 公钥
Git Bash 关联已存在的 SSH 公钥
更换电脑,将上一台电脑的公私钥复制过来,然后在新的电脑上面,git bash做关联操作。
未绑定的时候,使用git clone 命令报错:
gitbash提示报错:kex_exchange_identification: read: Connection reset by peer fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
以下命令都在Git Bash客户端执行。
生成新的 SSH 密钥对
ssh-keygen -t ed25519 -C "your_email@example.com"
或者使用 RSA 算法(较老但兼容性更好):
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
## 1. 检查现有密钥文件
```bash
ls -al ~/.ssh/
```
drwxr-xr-x 1 H 197609 0 12月 14 2022 ./
drwxr-xr-x 1 H 197609 0 1月 26 11:09 ../
-rw-r--r-- 1 H 197609 3243 12月 14 2022 id_rsa
-rw-r--r-- 1 H 197609 738 12月 14 2022 id_rsa.pub
-rw-r--r-- 1 H 197609 787 1月 13 13:54 known_hosts
查看是否存在以下文件:
- 公钥文件:`id_rsa.pub`、`id_ed25519.pub` 等
- 私钥文件:`id_rsa`、`id_ed25519` 等
## 2. 启动 SSH 代理服务
```bash
# 启动 SSH 代理
eval "$(ssh-agent -s)"
Agent pid 535
# 添加现有的私钥到 SSH 代理
ssh-add ~/.ssh/id_rsa
# 或者如果是 ed25519 算法
ssh-add ~/.ssh/id_ed25519
```
Identity added: /c/Users/H/.ssh/id_rsa (/c/Users/H/.ssh/id_rsa)
## 3. 验证密钥是否已加载
```bash
# 列出已加载的密钥
ssh-add -l
```
#demo
4096 SHA256:YzbUcOFZcjLlw4qpAiWPU23ti /c/Users/H/.ssh/id_rsa (RSA)
## 4. 复制公钥内容
```bash
# 显示公钥内容
cat ~/.ssh/id_rsa.pub
# 或使用剪贴板复制 (复制内容到粘贴板,可以直接粘贴)
clip < ~/.ssh/id_rsa.pub
```
#demo
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEAydQSPd7L3kof3jNJcdg+fiWqxfEF2+/4ovKUdQSLXD3mzt9AGND3zMIBiIaf7HfHtaqQnuJNPQ0y0Ibq4F//HWonLho7cIjRxXhg5oY/P27aYhoemFHM59GevZtD++///aVpuAWTz5kGT6K3AJi2dJKb5pgd4GfHyHS1HXr+UxqUs/iAmtFDU/++S4ET0J347oYOFyaUeVn/MUAqRP92ou2RHt9n3NxiuBp4nUJ9CO7BneIGt5PfmlF6/f3qkxTobj0xQ6KXg9vSe41Tw5J7ZJujoWxyHJkx/Utxy2V2HTL8= tester@qq.com
## 5. 在 Git 平台配置公钥 (git bash公钥设置,已经存在了,不能重复添加,会在界面上面有提示。)
将上述命令输出的公钥内容添加到:
- **GitHub**: Settings → SSH and GPG keys → New SSH key
- **GitLab**: Settings → SSH Keys
- **Gitee**: 设置 → SSH公钥
## 6. 测试连接
```bash
# 测试与 Git 服务商的连接
ssh -T git@github.com
```
demo:
$ ssh -T git@xx.45.1.1
Welcome to GitLab, @tester!
## 7. 配置 Git 用户信息(如果需要)
```bash
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
```
## 注意事项
- 确保私钥文件权限正确(600)
- 公钥文件权限应为 644
- 不同 Git 服务商可能需要不同的 SSH 配置
这样就完成了已有 SSH 公钥与 Git 的关联设置。
浙公网安备 33010602011771号