由于公司团队使用 GitLab 来托管代码,同时,个人在 Github 上还有一些代码仓库,可公司邮箱与个人邮箱是不同的,由此产生的 SSH key 也是不同的,这就造成了冲突 ,文章提供此类问题的解决方案:如何在一台机器上面同时使用 Github 与 Gitlab 的服务?

生成GitHub/GitLab 的 SSH Key

$ ssh-keygen -t rsa -f ~/.ssh/id_rsa_github -C "123456@qq.com"
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitlab -C "admin@example.com"

检查key是否生成,执行下面的命令,有id_rsa_githubid_rsa_gitlab以及他们的公钥文件就是成功了。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
$ ls ~/.ssh

CentOS7上GitHub/GitLab多帐号管理SSH Key 随笔 第1张

添加private key

$ ssh-add ~/.ssh/id_rsa_github
$ ssh-add ~/.ssh/id_rsa_gitlab

如果执行ssh-add时提示"Could not open a connection to your authentication agent",可以先执行命令:
$ ssh-agent bash,然后再运行ssh-add命令。

# 可以通过 ssh-add -l 来确私钥列表
$ ssh-add -l
 
# 可以通过 ssh-add -D 来清空私钥列表
$ ssh-add -D

修改配置文件

$ vi ~/.ssh/config

# github
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_github
 
# gitlab
Host gitlab.example.com
    HostName gitlab.example.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_gitlab

上传public key 到 GitHub/GitLab

GitHub设置过程如下

登录github,点击右上方的图标,点击“Settings”
CentOS7上GitHub/GitLab多帐号管理SSH Key 随笔 第2张

选择“SSH and GPG keys”,点击“New SSH key”,在出现的界面中填写SSH key的名称,填一个你自己喜欢的名称即可,然后将上面拷贝的 ~/.ssh/id_isa_github.pub 文件内容粘帖到 key 一栏,在点击“Add SSH key”按钮就可以了。

GitLab设置过程如下:

点击“Profile Settings”

CentOS7上GitHub/GitLab多帐号管理SSH Key 随笔 第3张

点击“SSH Keys”,添加SSH key

CentOS7上GitHub/GitLab多帐号管理SSH Key 随笔 第4张

测试

添加过程github会提示你输入一次你的github密码 ,确认后即添加完毕。

# 测试github
$ ssh -T git@github.com
 
# 测试gitlab
$ ssh -T git@gitlab.example.com
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄