让一个客户端支持多个git账户

1.在客户端中生成第一个ssh密钥,下面的邮箱地址,需替换成自己的邮箱(如已经生成过,此步骤忽略)

ssh-keygen -t rsa -C “[email protected]

系统会提示输入密钥的保存路径以及密码,这里我们保持默认,一路回车。

2.查看public key

cat ~/.ssh/id_rsa.pub

3.将密钥添加到你的git服务器(github、git.oschina、coding等)的my ssh处。

至此第一个ssh密钥生成并添加成功,下面我们来添加第二个git密钥

4.在客户端再次生成一个ssh密钥,下面的邮箱地址,替换成自己的另一个邮箱

ssh-keygen -t rsa -C “[email protected]

5.系统会做出如下提示,如果我们敲回车,将会提示是否覆盖,我们要两个ssh密钥生效,自然不允许覆盖,所以这里我们不能直接回车

Enter file in which to save the key (/Users/liyang/.ssh/id_rsa):

6.这里我们给id_rsa重新定义一个名字id_rsa_2,密码依旧默认(默认为空)

Enter file in which to save the key (/Users/liyang/.ssh/id_rsa):/Users/liyang/.ssh/id_rsa_2

7.查看public key

cat ~/.ssh/id_rsa_2.pub

8.将密钥添加到你的git服务器(github、git.oschina、coding等)的my ssh处。

9.但是默认情况下,系统只会去找命名为id_rsa的key,要支持第二个key,就要额外设置一下了,我们在~/.ssh文件夹下打开或创建config文件

vim config

10.在此文件中输入以下配置,具体内容根据实际环境修改。

Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa

Host github2
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_2

 其规则就是:从上至下读取config的内容,在每个Host下寻找对应的私钥。这里将GitHub SSH仓库地址中的[email protected]替换成新建的Host别名如:github2,那么原地址是:[email protected]:xxx/xxx.git,替换后应该是:git@github2:xxx/xxx.git.