我想使用多个私钥连接到不同的服务器或同一服务器的不同部分(我的用途是服务器的系统管理、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/config:

Host myshortname realname.example.com
    HostName realname.example.com
    IdentityFile ~/.ssh/realname_rsa # private key for realname
    User remoteusername

Host myother realname2.example.org
    HostName realname2.example.org
    IdentityFile ~/.ssh/realname2_rsa  # different private key for realname2
    User remoteusername

然后您可以使用以下连接:

ssh myshortname

SSH我的其他

等等。

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

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

我同意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进行测试

在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