一、前置知识
-
一个 SSH 公钥 可以同时添加到多个平台(GitHub、Gitee、GitCode)。
-
如果你选择为每个平台生成 单独的 SSH key,就必须在
~/.ssh/config
中指定好对应关系。 -
每个平台只认你在账户后台添加的公钥,私钥保存在本地。
二、当前情况
-
id_rsa
→ GitHub(已有密钥1) -
id_ed25519
→ Gitee(已有密钥2) -
新生成的
id_ed25519_gitcode
→ GitCode(将生成的第三个密钥)
三、生成 GitCode 专用密钥
在终端(git终端 git bash)执行(邮箱最好使用 GitCode 的提交邮箱 example@gitcode.net
(这里的邮箱替换成自己的实际提交邮箱)):
ssh-keygen -t ed25519 -C "example@gitcode.net" -f ~/.ssh/id_ed25519_gitcode
这样会生成:
-
~/.ssh/id_ed25519_gitcode
(私钥) -
~/.ssh/id_ed25519_gitcode.pub
(公钥)
四、添加公钥到 GitCode(git终端 git bash 执行)
复制公钥内容:这个命令会输出公钥的内容,将输出内容复制。
cat ~/.ssh/id_ed25519_gitcode.pub
然后登录 GitCode(记得登录.net而不是.com) → 设置 → SSH 公钥 → 新建 → 粘贴保存。
五、配置 ~/.ssh/config
(这个文件在C/用户/86153/.ssh目录下)
编辑 ~/.ssh/config
文件,写入以下内容:
# GitHub Host github.com HostName ssh.github.com User git Port 443 IdentityFile ~/.ssh/id_rsa # Gitee Host gitee.com HostName gitee.com User git IdentityFile ~/.ssh/id_ed25519 # GitCode Host gitcode.net HostName gitcode.net User git IdentityFile ~/.ssh/id_ed25519_gitcode
注意:
GitHub 配置里必须保留
ssh.github.com:443
,因为原本就是走 443 端口。GitCode 的 Host 要写 gitcode.net(不是 gitcode.com)。
六、验证配置
逐个测试:
ssh -T git@github.com ssh -T git@gitee.com ssh -T git@gitcode.net
预期结果:
-
GitHub
Hi <用户名>! You've successfully authenticated, but GitHub does not provide shell access.
-
Gitee
Hi <用户名>! You've successfully authenticated, 后面省略......
-
GitCode
Welcome to GitLab,后面省略......
这三个提示都是 正常现象,说明认证成功。(只要输出内容中出现Hi或者welcome等内容就代表密钥配置连接成功)
七、常见问题排查
-
Permission denied (publickey)
-
检查
~/.ssh/config
的 Host 是否和仓库地址一致。 -
确认本地公钥已添加到对应平台。
-
-
不知道用哪个邮箱生成 key?
-
建议用平台的 提交邮箱(GitCode 设置里显示的“提交邮箱”)。
-
-
一个密钥能不能多个平台共用?
-
可以。但最好每个平台一个密钥,使用不同的密钥更加安全,也方便区分。
-