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

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

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

这很麻烦。

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


当前回答

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

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

我曾经遇到过这个问题,当时我有两个Bitbucket帐户,想要为两个帐户存储单独的SSH密钥。这对我来说很管用。

我创建了两个单独的ssh配置,如下所示。

Host personal.bitbucket.org
    HostName bitbucket.org
    User git
    IdentityFile /Users/username/.ssh/personal
Host work.bitbucket.org
    HostName bitbucket.org
    User git
    IdentityFile /Users/username/.ssh/work

现在当我必须从我的工作帐户克隆一个存储库时,命令如下所示。

git clone git@bitbucket.org:teamname/project.git

我必须修改这个命令:

git clone git@**work**.bitbucket.org:teamname/project.git

同样,从我的个人帐户克隆命令必须修改为

Git克隆git@personal.bitbucket.org:name/personalproject.git

更多信息请参考这个链接。

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

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

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

 ssh aws

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克隆命令),你可以把它从配置中去掉。

点击这里查看更多信息