我想使用多个私钥连接到不同的服务器或同一服务器的不同部分(我的用途是服务器的系统管理、Git管理和同一服务器中的正常Git使用)。我尝试简单地将密钥堆叠在id_rsa文件中,但没有用。

显然,要做到这一点,一个简单的方法是使用命令

ssh -i <key location> login@server.example.com 

这很麻烦。

有什么建议可以让你做这件事更容易一些吗?


当前回答

GitHub上的多个键对

1.0 SSH配置文件

1.1创建~/.ssh/config

1.2 chmod 600 ~/。ssh / config(必须)

1.3在文件中输入如下内容:

主机披萨 主机github。com 选择公共关系 IdentityFile ~ / . ssh / privatekey1

案例A:全新的Git克隆

使用此命令克隆Git:

$ git clone git@pizza:yourgitusername/pizzahut_repo.git

注意:如果以后要更改.ssh/config的主机名“pizza”,进入Git克隆文件夹,编辑.git/config文件URL行(见case B)

情况B:已经有Git克隆文件夹

2.1进入克隆文件夹,进入“。git”文件夹

2.2编辑配置文件

2.3将URL从*old更新为new:

(Old) URL = git@github.com:yourgitusername/pizzahut_repo.git

(New) URL = git@pizza:yourgitusername/pizzahut_repo.git

其他回答

前面的回答已经正确地解释了如何创建一个配置文件来管理多个ssh密钥。我认为,还需要解释的重要事情是在克隆存储库时用别名替换主机名。

假设,您公司的GitHub帐户的用户名是abc1234。 假设你的个人GitHub账户的用户名是jack1234

并且,假设您已经创建了两个RSA密钥,即id_rsa_company和id_rsa_personal。因此,您的配置文件将如下所示:

# Company account
Host company
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_company

# Personal account
Host personal
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal

现在,当你从公司的GitHub帐户克隆存储库(命名为demo)时,存储库URL将类似于:

Repo URL: git@github.com:abc1234/demo.git

现在,在做git克隆时,你应该把上面的存储库URL修改为:

git@company:abc1234/demo.git

注意github.com现在是如何被我们在配置文件中定义的别名“company”所取代的。

同样,您必须根据配置文件中提供的别名修改个人帐户中存储库的克隆URL。

您可以在~/中创建一个名为config的配置文件。ssh文件夹。它可以包含:

Host aws
    HostName *yourip*
    User *youruser*
    IdentityFile *idFile*

这将允许您像这样连接到机器

 ssh aws

正如Atlassian博客页面上提到的, 在.ssh文件夹中生成一个配置文件,包括以下文本:

#user1 account
 Host bitbucket.org-user1
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/user1
     IdentitiesOnly yes

 #user2 account
 Host bitbucket.org-user2
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/user2
     IdentitiesOnly yes

然后,您可以简单地用后缀域签出,在项目中,您可以在本地配置作者名称等。

您可以指示ssh在连接时连续尝试多个键。方法如下:

$ cat ~/.ssh/config
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_rsa_old
IdentityFile ~/.ssh/id_ed25519
# ... and so on

$ ssh server.example.com -v
....
debug1: Next authentication method: publickey
debug1: Trying private key: /home/example/.ssh/id_rsa
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/example/.ssh/id_rsa_old
debug1: read PEM private key done: type RSA
....
[server ~]$

这样就不必指定哪个密钥适用于哪个服务器。它会使用第一个工作键。

此外,只有当给定的服务器愿意接受密钥时,您才可以输入密码短语。如上所述,ssh不会尝试询问.ssh/id_rsa的密码,即使它有密码。

当然,它不会像其他答案那样胜过每个服务器的配置,但至少您不必为您连接的所有服务器和每个服务器添加配置!

我同意Tuomas使用ssh-agent。我还想为工作添加第二个私钥,这个教程对我来说非常有效。

步骤如下:

$ ssh-agent bash $ ssh-add /path。到/private/key,例如ssh-add ~/.ssh/id_rsa 通过$ ssh-add -l验证 使用$ssh -v <主机url>例如ssh -v git@assembla.com进行测试