现在工作中有这样一个需求,就是我需要管理多个gitlab 或者 github 账号上面的代码,但不同的账号不能共用一个SSH Key,例如一个已经被某账号使用的Key,登陆另外一个账号添加此Key时,会报:Fingerprint has already been taken 错误。
默认情况下,我们在本地电脑生成的密钥都是 id_rsa 和 id_rsa.pub ,git 默认情况下也只会读取这个私钥,所以我们需要修改一些配置来支持多个SSH Key。
例如:有a.com、b.com两个项目,两项目所属两个不同的gitlab账号,a.com使用默认的配置及密钥,现在我们来为b.com添加新的密钥。
步骤一:
ljh@pc:~/.ssh$ ssh-keygen -t rsa -C "xxx@qq.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ljh/.ssh/id_rsa): id_rsa_bproject
在创建密钥时不能一直回车,默认的那份密钥是一直回车就能生成的,但这一次需要给新密钥生成不同的名称,然后再回车。
ljh@pc:~/.ssh$ ll
总用量 32
drwx------ 2 ljh ljh 4096 2月 27 11:39 ./
drwxr-xr-x 40 ljh ljh 4096 2月 27 11:44 ../
-rw-r--r-- 1 ljh ljh 157 2月 27 11:39 config
-rw------- 1 ljh ljh 1679 6月 25 2018 id_rsa
-rw------- 1 ljh ljh 1679 2月 25 18:28 id_rsa_bproject
-rw-r--r-- 1 ljh ljh 398 2月 25 18:28 id_rsa_bproject.pub
-rw-r--r-- 1 ljh ljh 395 6月 25 2018 id_rsa.pub
-rw-r--r-- 1 ljh ljh 888 2月 27 11:29 known_hosts
可以看到已经生成了新的SSH Key。
步骤二:
ssh-agent是一个私钥的管理工具,当我们需要通过不同的私钥去连接不同的服务器时,需要我们手动输入私钥密码,ssh-agent可以免去这项工作,那么我们需要将新的key 添加到ssh-agent里面管理,可以通过ssh-add命令,首先我们看下里面有哪些key:
ljh@pc:~/.ssh$ ssh-add -l
2048 SHA256:xxx /home/ljh/.ssh/id_rsa (RSA)
默认情况下id_rsa已经存在里面,那么我们此时应该把上面新建的key也添加到里面:
ljh@pc:~$ ssh-add /home/ljh/.ssh/id_rsa_bproject
Identity added: /home/ljh/.ssh/id_rsa_bproject (/home/ljh/.ssh/id_rsa_bproject)
此时再用上面的ssh-add -l 查看,发现新的key也添加到了管理。
步骤三:
在.ssh/ 目录里创建一个config文件,通过配置信息告诉git什么情况下使用新的key:
ljh@pc:~/.ssh$ touch config
ljh@pc:~/.ssh$ vim config
添加下面内容:
# gitlab
Host gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_bproject
User ljh
User填写的是gitlab账号。
步骤四:
进入b.com项目,git init 初始化后,通过 git config 配置 user.name 与 user.email 信息,注意这是设置当前项目所在gitlab账号的用户名及邮箱信息,我们平时可能会使用git config --global 来设置全局的,全局的就当是默认,不需要unset。
ljh@pc:/www/b.com$ git config user.name "ljh"
ljh@pc:/www/b.com$ git config user.email "xxx@qq.com"
ljh@pc:/www/b.com$ git config --list
配置完成后,通过git config --list 查看当前项目的git 配置,发现会有重复的user.name 与user.email配置,这个不需要担心,最上面的应该是读取的全局配置信息,下面的是自己当前项目设置的,配置信息从下而上会覆盖掉。
到此,将 id_rsa_bproject.pub 这个新的SSH Key 公钥添加到 ljh 这个gitlab账号上面就可以正常使用了。