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

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

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

这很麻烦。

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


当前回答

这是我从sajib-khan的回答中得到的灵感。没有设置默认配置;这是我在GitLab上的个人账号,另一个是我的公司账号。以下是我所做的:

生成SSH密钥

ssh-keygen -t rsa -f ~/.ssh/company -C "name.surname@company.com"

编辑SSH配置

nano ~/.ssh/config
    Host company.gitlab.com
    HostName gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/company

删除缓存的SSH密钥

ssh-add -D

测试它!

ssh -T git@company.gitlab.com

欢迎来到GitLab, @hugo.sohm!

ssh -T git@gitlab.com

欢迎你的芳名…

使用它!

公司账户

git clone git@company.gitlab.com:group/project.git

个人/默认账户

git clone git@gitlab.com:username/project.git

这是我使用的源代码。

其他回答

对密钥使用ssh-agent。

重要提示:必须启动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代理。

您可以指示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的密码,即使它有密码。

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

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

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

点击这里查看更多信息