如何为具有同一主机的多个 gitlab 帐户使用多个 ssh 密钥

How to use multiple ssh keys for multiple gitlab accounts with the same host

我想在 Gitlab 网站上使用 2 个帐户,每个帐户都有不同的 ssh 密钥

我成功生成了密钥并将它们添加到 ~/.ssh 文件夹中 我创建了 ~/.ssh/config 文件并使用了其中一个,效果很好 我还可以通过编辑 ~/.ssh/config 文件

在两个键之间进行交换

问题是:我想同时使用它们,但是我发现所有教程都是关于不同主机的:/

实际上我的两个账户在同一个主机上

我如何编辑 ~/.ssh/config 文件以接受同一主机的两个帐户

注:我读了this question但我无法从中得到帮助

我的两个帐户是 username1username2 回购 URL 看起来像:git@gitlab.com:username1/test-project.git

我当前的 ~/.ssh/config 文件:

Host gitlab.com-username1
  HostName gitlab.com
  User git
  IdentityFile ~/.ssh/id_rsa

Host gitlab.com-username2
  HostName gitlab.com
  User git
  IdentityFile ~/.ssh/id_rsa_username2

更新 1:

1) 当我在 ~/.ssh/config 文件中使用一个键时,一切正常(但每次我想更改我使用的用户时都更新它很无聊)

2) 当我使用这条线时 ssh -T git@gitlab.com-username1 ssh -T git@gitlab.com-username2 它运行良好,return 一条欢迎信息

从 1) 和 2) 来看,我认为问题肯定出在 ~/.ssh/config 文件中,特别是在 Host 变量

更新二:(求解) 解决方法是编辑 .git/config 文件 [remote "origin"] url = git@gitlab.com:username1/test-project.git[remote "origin"] url = git@gitlab.com-username1:username1/test-project.git

并对 username2

做同样的事情

使用上面的 ~/.ssh/config 并将您使用 git 的 URL 更新为第一个用户的 git@gitlab.com-username1:username1/test-project.git 和第二个用户的 git@gitlab.com-username2:username2/test-project.git (例如, git clone git@gitlab.com-username1:username1/test-project.git).

SSH 将在 ~/.ssh/config 中查找 gitlab.com-username1 别名,并将使用正确的主机名和 SSH 密钥文件。

另一种方法是只使用一个用户 pushing/pulling 并授予该用户所需的权限。

您已完成 ssh 配置。首先,检查它是否有效:

ssh -T git@gitlab.com-username1
ssh -T git@gitlab.com-username2

在这两种情况下都应该成功。如果不是,则密钥设置不正确。验证相应用户的密钥在 gitlab 上。

如果有效,请转到您的 git 存储库并打开 .git/config。它会有一些像这样的部分:

[remote "origin"]
  url = git@gitlab.com:username1/test-project.git

替换为

[remote "origin"]
  url = git@gitlab.com-username2:username1/test-project.git

(或 username1,如果您想使用此用户名连接)。然后它应该允许你推。