背景
gitlab可以管理在公司开发代码,但是很多情况下,我们需要clone一些优秀的开源项目,这时候就需要在一台设备上同时可以访问github和gitlab了。
由于github和gitlab用户名不一样,如果只生成一个秘钥,无法做到一个秘钥分别在gitlab和github上使用。因此需要考虑分别生成不同账号的秘钥。
配置步骤
找到位于用户下的.ssh文件
cd ~/.ssh
设置全局的name和email
git config --global user.name 'zhangsan'
git config --global user.email 'zhangsan@demo.com'
为gitlab和github生成秘钥
注意: 需要为两者命名不同的id_rsa文件名。
ssh-keygen -t rsa -C 'zhangsan@demo.com' // GitLab
// Enter file in which to save the key (/Users/tomatoro/.ssh/id_rsa): id_rsa_gitlab
ssh-keygen -t rsa -C 'zhangsan@163.com' // GitHub
// Enter file in which to save the key (/Users/tomatoro/.ssh/id_rsa): id_rsa_github
由于本机一开始是有gitlab的秘钥,因此我这里仅仅增加github的秘钥。
粘贴秘钥到github和gitlab
将id_rsa.pub文件内容复制到gitlab,id_rsa_github.pub文件内容复制到github。
gitlab如下图:
github如下图:
config文件管理key
【关键点】 需要一个config文件来管理这两个key,以让git知道分配给谁,在.ssh目录下创建config文件。
touch ~/.ssh/config
Host github.com
HostName ssh.github.com
User zhangsan@163.com // github用户名
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github
Port 443 // 端口必须配置
Host git.demo.com // 公司gitlab域名
HostName git.demo.com
User zhangsan@demo.com
IdentityFile ~/.ssh/id_rsa
// 本身内网访问gitlab,故无需配置Port
至此。即可正常访问Github和Gitlab了。
结束语
经过上述一顿操作,再也不用当需要github上代码时,手动download源代码zip包了。
常思考,勤动脑。