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

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

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

这很麻烦。

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


当前回答

您可以尝试这个sshmulti npm包来维护多个SSH密钥。

其他回答

现在,使用最新版本的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/*

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

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

Generate an SSH key: $ ssh-keygen -t rsa -C <email1@example.com> Generate another SSH key: $ ssh-keygen -t rsa -f ~/.ssh/accountB -C <email2@example.com> Now, two public keys (id_rsa.pub, accountB.pub) should be exists in the ~/.ssh/ directory. $ ls -l ~/.ssh # see the files of '~/.ssh/' directory Create configuration file ~/.ssh/config with the following contents: $ nano ~/.ssh/config Host bitbucket.org User git Hostname bitbucket.org PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa Host bitbucket-accountB User git Hostname bitbucket.org PreferredAuthentications publickey IdentitiesOnly yes IdentityFile ~/.ssh/accountB Clone from default account. $ git clone git@bitbucket.org:username/project.git Clone from the accountB account. $ git clone git@bitbucket-accountB:username/project.git

注意:由于User git指令,你可以省略repo URL的git@部分,像这样缩短你的克隆命令:

    $ git clone bitbucket-accountB:username/project.git

这是该指令的唯一目的。如果你不需要它(例如,你总是从网站复制粘贴git克隆命令),你可以把它从配置中去掉。

点击这里查看更多信息

在CentOS 6.5上运行OpenSSH_5.3p1和OpenSSL 1.0.1e-fips,我通过重命名密钥文件来解决这个问题,这样它们都没有默认名称。

我的.ssh目录包含id_rsa_foo和id_rsa_bar,但没有id_rsa等。

重要提示:必须启动ssh-agent

在使用ssh-add之前,必须启动ssh-agent(如果它还没有运行),如下所示:

eval `ssh-agent -s` # start the agent

ssh-add id_rsa_2 # Where id_rsa_2 is your new private key file

注意,eval命令在Windows上的Git Bash上启动代理。其他环境可能使用一个变体来启动SSH代理。