前言
在我们当前对git 的使用中,有免费的github远程仓库,工作中也基本用gitlab内部仓库,还有一些人会用到私有仓库,其中每个库在进行代码的clone和push等操作的时候,均需要配置本地的ssh key,如果没配置的话,便每次都需要用户名密码验证,并且经常验证失败(未知原因)。
key的生成我们通常这样。
ssh-keygen -t rsa -C "[email protected]”
经过多步的操作后,会在 ~/.ssh/ (linux) ,C:\Users\\username\.ssh\ (windows)下生成公钥和私钥,id_rsa id_rsa.pub。然后我们将其中的key值配置到我们远程仓库的key中即可,这样就可以使用[email protected] 作为登陆账号的远程仓库如github、私有仓库等。
上述的操作确实可以解决使用同一个邮箱账户配置git ssh key的问题,但如果我们的机器不仅仅使用github,还需要使用到公司的gitlab呢?一般公司都是用企业邮箱注册的gitlab,这样使用通用邮箱生成的ssh key便无法通用,从而还需要再使用 ssh-keygen -t rsa -C "example@企业邮箱.com”,生成key再添加?,这样便会覆盖到之前的key,导致无法同时使用多个key。
正文
如何解决git配置多个ssh key时如何解决冲突的问题,即每次生成key的时候,给key取非默认名,然后修改ssh key的配置文件即可。
1.首先生成不同的key名
如github key
ssh-keygen -t rsa -C "[email protected]” -f ~/.ssh/github_id-rsa
如gitlab key
ssh-keygen -t rsa -C "examlpe@企业邮箱.com” -f ~/.ssh/gitlab_id-rsa
这样在相应的目录下~/.ssh/ (linux) ,C:\Users\\username\.ssh\ (windows),生成了两种key。
2.配置config
其次我们需要在目录: ~/.ssh/ (linux) ,C:\Users\\username\.ssh\ (windows),创建config文件,并且配置ssh key的路由策略,其中linux如下:
# gitlab
Host gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gitlab_id-rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id-rsa
widows如下:(windows下配置~/.ssh不识别)
# 配置github.com
Host github.com
HostName github.com
IdentityFile C:\\Users\\username\\.ssh\\github_id-rsa
PreferredAuthentications publickey
# 配置gitlab.com
Host gitlab.com
HostName gitlab.com
IdentityFile C:\\Users\\username\\.ssh\\gitlab_id-rsa
PreferredAuthentications publickey
3.配置远程仓库key,测试ssh key是否通过
在远程仓库的个人配置中,将key存入,并且使用ssh -T [email protected],是否会按照用户名验证即可。
结语
完事。