在 GitHub 设置新项目部署公钥,结果发现死活设置不了,提示已存在。

研究了一番,发现是因为 GitHub 针对不同的项目只能设置不同的公钥。蛋疼,没法偷懒了。

解决方案

解决办法就是生成多个 SSH 密钥对,然后给不同的项目设置不同部署公钥,再在项目的 Git 配置中设置 pull 时使用指定的密钥就可以了。

不多说了,上代码。

假设我们已经有一个项目,已经部署好了,使用的默认的 id_ras 密钥对。

现在需要部署新项目了,首先生成一个密钥对,我们随便起个名字就叫 crowall(我还是放到默认的 /root/.ssh 目录下):

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/crowall
Enter passphrase (empty for no passphrase):

生成好了以后,就可以看到这个密钥对了。

$ ll  ~/.ssh/ | grep crowall
-rw------- 1 root root 2.6K Oct 31 08:42 crowall
-rw-r--r-- 1 root root  561 Oct 31 08:42 crowall.pub

将公钥(即 /root/.ssh/crowall.pub)的文件内容作为部署公钥添加到 GitHub 中去。

2023-10-31T08:45:31.png

下面就是本地配置了。

进入项目目录,执行以下命令:

git config core.sshCommand 'ssh -i /root/.ssh/crowall -p 22'

就可以设置该项目使用指定的 crowall 文件作为密钥了。

拉去项目发现正常执行了。

当然,如果修改了 git remote 的地址,需要执行:

# git branch --set-upstream-to=origin/远程分支名称 本地分支名称
git branch --set-upstream-to=origin/main main

来将本地的分支重新与远程分支绑定。

问题解决。

标签: ssh, github, 部署公钥, Deploy keys