一客户端使用多个密钥对登录多个主机的解决方案.


来自:https://www.zhihu.com/question/29864641/answer/124695532
 
比如 github 、bitbucket ,出现了好几次无法提交和拉取的问题,我才意识到我多次修改了 id_rsa 文件,为不同的 git 服务创建 ssh key 的同时也覆盖了之前 git 服务器的 key 。心想肯定有办法让多个服务共存

创建密钥

1.创建一个密钥

$ ssh-keygen -t rsa

2.输入保存ssh key 密钥的文件名称 id_rsa_github 。

Enter file in which to save the key (/root/.ssh/id_rsa):/root/.ssh/id_rsa_aaa

3.输入两次密码,要求最低不能低于8位。

Enter passphrase (empty for no passphrase):
Enter same passphrase again:


重复上面的步骤可以创建多个密钥,比如你有多个git账户

id_rsa_github
id_rsa_bitbucket
id_rsa_oschina

添加到 ssh-agent

用ssh-add命令把创建的密钥添加到 ssh-agent 里

$ ssh-add ~/.ssh/id_rsa_github
$ ssh-add ~/.ssh/id_rsa_bitbucket
$ ssh-add ~/.ssh/id_rsa_oschina

你可以用ssh-add -l来查看一下添加效果,一般会出现下面的提示信息

2048 SHA256:ueU7NSaLTzfKNMKL3EVkBKqK2/bvr/ewdNVTmBYZtxg /Users/YourName/.ssh/id_rsa_github (RSA)
2048 SHA256:xGAMHLe5Un5LLWiXp6GI84CVn23sD9g+EQBjXMQP34YA /Users/YourName/.ssh/id_rsa_bitbucket (RSA)
2048 SHA256:lJfTU9j6JfkMSM4vJpk5BdsARzkRA/d05aUnc2BdBeg /Users/YourName/.ssh/id_rsa_oschina (RSA)

这就证明你之前添加都已经生效了。

当然如果这里出现什么问题,你也可以用 ssh-add -d 来删除某个id_rsa

保存公钥到 git 服务

打开对应的git服务网站管理页面把对应的公钥提交保存到代码管理服务器(.pub 结尾)

添加 ssh 配置文件

在 ~/.ssh 目录创建 config 配置文件

nano ~/.ssh/config

添加配置信息

Host github.com
    HostName        github.com
    User            git
    IdentityFile    /Users/YourName/.ssh/id_rsa_github

Host bitbucket.org
    HostName        bitbucket.org
    User            git
    IdentityFile    /Users/YourName/.ssh/id_rsa_bitbucket

Host oschina.net
    HostName        oschina.net
    User            git
    IdentityFile    /Users/YourName/.ssh/id_rsa_oschina
原文地址:https://www.cnblogs.com/lovesKey/p/10778446.html