发布于 

同一台机器使用多个gitee账号开发

背景:在个人开发的计算机上,一般只使用一个默认的ras秘钥对,但Gitee(GitHub也是如此,此处以Gitee为例)不允许多个gitee账号设置同一ssh公钥。

目标:在同一台机器上开发多个gitee账号下的项目。

解决方法:为不同的git项目指定不同的rsa秘钥对。

操作步骤:

1、生成一个新的自定义ssh密钥对。使用-C设置自定义的秘钥描述,并且,在交互弹出的文件保存路径时,要使用自定义的路径。如果直接回车会覆盖已有的id_rsa秘钥!!!

$ ssh-keygen -t rsa -C 'YourCustomizedName'
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zgd/.ssh/id_rsa): /Users/zgd/.ssh/customized_rsa --这里可改成自定义的秘钥名称,与默认的id_rsa区分开来
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
......

2、打开浏览器,使用第2个账号登入Gitee,添加这个新的ssh公钥。(具体可参加Gitee教程

3、将第2个Gitee账号下的项目clone到本地,例如:

$ git clone git@gitee.com:fatmouse007fatmouse007/clbench.git

此处改为你自己的工程路径,注意:必须使用git开头的仓库地址,这表示使用git协议,而不是https,只有使用git协议才会走ssh秘钥认证流程。

4、修改~/.ssh/config配置,为不同的url指定不同的秘钥,这一步是关键。

示例如下:

Host gitee.com
HostName gitee.com
User git
IdentityFile /Users/zgd/.ssh/163.rsa
IdentitiesOnly yes
Host fatmouse007.gitee.com
HostName gitee.com
User git
IdentityFile /Users/zgd/.ssh/fatmouse007_rsa
IdentitiesOnly yes

每一个配置项包含Host名称,以及实际的HostName,以及为这个url指定的私钥文件IdentityFile。以第2个配置项为例,当输入给ssh的url是fatmouse007.gitee.com,且用户名是git时,ssh会查找config,将url中 fatmouse007.gitee.com 部分替换为HostName gitee.com,并选择fatmouse007_rsa作为登录秘钥。如此,就实现了一个从自定义url到{实际url,自定义秘钥}的映射。

5、设置git工程的remote url中的真实HostName为自定义的Host

$ git remote -v
origin git@gitee.com:fatmouse007fatmouse007/clbench.git (fetch)
origin git@gitee.com:fatmouse007fatmouse007/clbench.git (push)

$ git remote set-url origin git@fatmouse007.gitee.com:fatmouse007fatmouse007/clbench.git

这里将gitee.com替换成了fatmouse007.gitee.com,只是一个示例,具体请按照你实际的url替换。

6、验证配置是否成功

$ ssh -T git@fatmouse007.gitee.com
Hi fatmouse007! You've successfully authenticated, but GITEE.COM does not provide shell access.

以上表示ssh秘钥配置成功,以后可以直接git push