一个git如何同时绑定gitlab与github

2,390 阅读2分钟

需求

公司电脑git为gitlab,但又想往github上传东西,需要同时使用gitlab与github.

解决

首先新建一个SSH Key

查看已有 密钥

Mac 下输入命令 ls ~/.ssh/,如果此时git已经配置过gitlab,看到 id_rsa 与 id_rsa_pub 则说明已经有一对密钥。

ls ~/.ssh/

image.png 那此时应生成新的公钥,预备给github使用

要保证与已有密钥文件不同,我们此次命名为id_rsa_hy,最后的参数为注册github的邮箱

ssh-keygen -t rsa -f ~/.ssh/id_rsa_hy -C "12345@qq.com"

此时直接一直回车就行

上面命令执行完,~/.ssh下就出现了刚才的文件

image.png

此时复制'id_rsa_hy.pub'中的内容到github中新建一个SSH Key


设置不同 Host 对应同一 HostName 但密钥不同

在 .ssh 文件夹下新建 config 文件并编辑,令不同 Host 实际映射到同一HostName,但密钥文件不同。

cd ~
cd .ssh
touch config
vim config

按i键进入编辑状态,输入以下代码

Host github.com
HostName github.com
User xxx@xxx.com       //user后边为github的邮箱
IdentityFile ~/.ssh/id_rsa_hy

Host gitlab.xxx.cn    //host后边为公司gitlab域名
HostName gitlab.xxx.cn   //同上为公司gitlab域名
User xxx@xxx.com          //user后为gitlab的邮箱
IdentityFile ~/.ssh/id_rsa

测试SSH连接

ssh -T git@github.com
ssh -t git@gitlab.xxx.cn

提示成功则表示连接成功啦!

此时可能会有:

The authenticity of host 'github.com (192.30.255.112)' can't be established.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? 

只需要在最后,输入yes

Are you sure you want to continue connecting (yes/no/[fingerprint])?  //输入yes,回车

最后,push/pull时,可推送到相应的仓库

由于个人gitlab使用更多,所以将全局配置(global)配置为gitlab

后续单独建立自己仓库时,再使用本地配置对应的账号

// 全局配置
$ git config --global user.name  'gitlab账号名' 
$ git config --global user.email  'gitlab账号邮箱'

// 本地配置
$ git config --local user.name  'github账号名'   
$ git config --local user.email  'github邮箱'