可怕,竟然能够配置多个git sshkey

前言

有一天小猪心血来潮,以为以前的 github 帐号id (pig) 不够碎,因而注册了一个新的 github 帐号 (weijiezhu) ,而且按照 github help 的套路完成了ssh的配置。由于同一个 sshkey (id_rsa) 不容许用在两个帐号当中,因而他生成了一个新的 sshkey (github_rsa)。html

当他写完代码以为本身很碎的时候,git push origin master 却返回了一个错误。react

$ git push origin master
ERROR: Permission to weijiezhu/react-scaffold.git denied to pig.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

因而乎他跑了一个测试git

$ ssh -T git@github.com
Hi pig! You've successfully authenticated, but GitHub does not provide shell access.

wocao,怎么仍是pig这个帐号呢。 明明弄了新的sshkey。github

通过一番捣腾,小猪仿佛发现了什么shell

ssh 使用了默认的 id_rsa 密钥进行加密,而这个好久之前建立的 sshkey 确实添加到 pig 帐号里面了。bash

当访问 github.com 的时候,github 服务会认为你就是pig这个帐户。ssh

噢~那好吧。把 pig 帐号里面的 sshkey 删掉吧,反正也不用了。而后把 id_rsa.pub 公钥从新添加到 weijiezhu 这个帐号里面,顺便删掉添加的 github_rsa.pub 公钥。ide

$ pbcopy < ~/.ssh/id_rsa.pub

再次提交代码。Absolutely done!gitlab

注意: 测试

上文和下文进阶的用户名和邮箱要配置好,若是有多个帐号,建议使用局部的。

git config user.name "用户名"  //在config后加上--global即全局
git config user.email "邮箱"

进阶

然而事情并无到此结束,装完逼还想跑那是不行的。小猪往后发现本身是一个念旧的人。他想要同时使用两个github。

那好吧,What a big deal~

这个时候咱们须要先找到 ~/.ssh/config 文件,而后往里面添加以下配置

Host pig.github.com
        HostName github.com
        IdentityFile ~/.ssh/github_rsa

咱们指定 pig.github.com 这个"做用域"下的ssh链接统一指向 github.com ,而且使用以前生成好的 github_rsa 这个密钥加密。

那么默认的就是使用 ~/.ssh/id_rsa 这个密钥加密咯。 而且HostName与“做用域”相同。这个就不须要咱们管了。

这个时候咱们测试一下呗。

$ ssh -T git@pig.github.com
Hi pig! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T git@github.com
Hi weijiezhu! You've successfully authenticated, but GitHub does not provide shell access.

: ) , orz , 这时候还差最后一步

就是修改一下咱们在 pig 克隆下来的项目的 remote “做用域” 。

$ git remote rm origin
$ git remote add origin git@pig.github.com:pig/tinynote.git // 注意是 pig.github.com 噢?, 把这个理解为一个“做用域”吧。
$ git push origin master
Everything up-to-date

一样的,对于使用不一样的git服务商,如(coding.net,gitlab等),能够“东施效颦”地使用上文的进阶方案来解决本地多个git帐号的问题。

这个时候小猪的队友惊呼 ,Jesus Christ, u save my ass ! orz.

对于ssh无密码登陆原理,或者.ssh/config配置不熟悉的能够自行google进行延伸阅读噢。

免责防喷: 若是上文描述哪里有问题,请不吝赐教!

相关文章
相关标签/搜索