SSH 配置 - 相同的主机但不同的密钥和用户名

usr*_*usr 47 ssh git github

我已经设置了两个 GitHub 帐户,但我无法让 ssh 密钥正常工作。我尝试了各种配置。


Host github_username1
    HostName github.com
    IdentityFile ~/.ssh/rsa_1
    User username1
Host github_username2
    HostName github.com
    IdentityFile ~/.ssh/rsa_2
    User username2
Run Code Online (Sandbox Code Playgroud)

git push

Permission denied (publickey).
fatal: The remote end hung up unexpectedly
Run Code Online (Sandbox Code Playgroud)

适用于 username1:

Host github.com
    HostName github.com
    IdentityFile ~/.ssh/rsa_1
    User username1
Host github.com
    HostName github.com
    IdentityFile ~/.ssh/rsa_2
    User username2
Run Code Online (Sandbox Code Playgroud)

git push 在 username2 的仓库中:

ERROR: Permission to username2/repo.git denied to username1.
fatal: The remote end hung up unexpectedly
Run Code Online (Sandbox Code Playgroud)

我也试着git pushIdentityFileUser设置下相同Host。输出与上一个配置相同。

我认为git会自动搜索主机“github.com”,因为遥控器就是这样。据说 Host 可以是你想要的任何东西(/sf/answers/268007771/)。有什么方法可以更改特定存储库应使用的 ssh 配置中的主机吗?

如果我可以从 ~/.ssh/config 解决这个问题,那将是理想的。

use*_*686 62

OpenSSH 客户端仅使用该Host行作为部分标识符,其他一切都是设置。如果连接到foo@bar.com,SSH 将不会搜索“ User foo”;它只会搜索“ Host bar.com”。

换句话说:如果您Host github_username2的 SSH 配置中有“ ”,那么您必须在 Git 远程服务器中使用相同的主机github_username2,而不是git@github.com.

但是,这不是导致身份验证失败的原因,在 的情况下github.com,SSH用户名必须是 " git"。GitHub SSH 服务器仅通过 SSH 密钥识别用户。


正确的 SSH 配置是:

Host github_username1
    Hostname github.com
    User git
    IdentityFile ~/.ssh/rsa_1
Host github_username2
    Hostname github.com
    User git
    IdentityFile ~/.ssh/rsa_2
Run Code Online (Sandbox Code Playgroud)

git配置:

[remote "origin"]
    url = git@github_username1:username2/repo.git
Run Code Online (Sandbox Code Playgroud)

替代 Git 配置:

[remote "origin"]
    url = git@github.com:username2/repo.git

[url "git@github_username1:"]
    insteadOf = git@github.com:
Run Code Online (Sandbox Code Playgroud)

注意:尽管我git在示例中的两个地方都指定了用户名,但它只需要指定一次——git@在 Git 中 URL 将优先User git于 SSH 配置。

  • 在某些情况下,您可能需要在每个 `host` 部分添加 `IdentitiesOnly=yes` 以确保 ssh 只会选择所选的身份文件并且不默认/尝试其他任何东西。 (3认同)
  • @TCB13 在我无法弄清楚为什么我的配置不起作用之后,您关于“IdentitiesOnly”的提示救了我。多谢! (2认同)
  • 此答案的替代方法是使用 [SSH 配置匹配器](https://unix.stackexchange.com/questions/691210/matching-both-user-and-host-simultaneously-in-ssh-config),它允许匹配独特的主机+用户组合。 (2认同)