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

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

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

这很麻烦。

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


当前回答

现在,使用最新版本的Git,我们可以在特定于存储库的Git配置文件中指定sshCommand:

  [core]
      repositoryformatversion = 0
      filemode = true
      bare = false
      logallrefupdates = true
      sshCommand = ssh -i ~/.ssh/id_rsa_user
   [remote "origin"]
      url = git@bitbucket.org:user/repo.git
      fetch = +refs/heads/*:refs/remotes/origin/*

其他回答

ssh-add ~/.ssh/xxx_id_rsa

请确保在添加之前进行测试:

ssh -i ~/.ssh/xxx_id_rsa username@example.com

如果你有任何错误的问题,有时改变文件的安全性有助于:

chmod 0600 ~/.ssh/xxx_id_rsa

在Ubuntu 18.04 (Bionic Beaver)上没有什么可做的。

成功创建第二个SSH密钥后,系统将尝试为每个连接查找匹配的SSH密钥。

你可以用下面这些命令创建一个新密钥:

# Generate key make sure you give it a new name (id_rsa_server2)
ssh-keygen

# Make sure ssh agent is running
eval `ssh-agent`

# Add the new key
ssh-add ~/.ssh/id_rsa_server2

# Get the public key to add it to a remote system for authentication
cat ~/.ssh/id_rsa_server2.pub

正如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

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

对我来说,在MacOs上,唯一可行的解决方案就是在文件~/.ssh/config中添加这个:

Host *
  IdentityFile ~/.ssh/your_ssh_key
  IdentityFile ~/.ssh/your_ssh_key2
  IdentityFile ~/.ssh/your_ssh_key3
  AddKeysToAgent yes

Your_ssh_key没有任何扩展名。不要使用.pub。

现在,使用最新版本的Git,我们可以在特定于存储库的Git配置文件中指定sshCommand:

  [core]
      repositoryformatversion = 0
      filemode = true
      bare = false
      logallrefupdates = true
      sshCommand = ssh -i ~/.ssh/id_rsa_user
   [remote "origin"]
      url = git@bitbucket.org:user/repo.git
      fetch = +refs/heads/*:refs/remotes/origin/*