git 如何知道要使用哪个 ssh 密钥进行操作?

How does git know which ssh key to use for its operations?

我在 ~/.ssh 中有 SSH 密钥。他们中的很多人实际上。所以我想知道 git 在尝试通过 git@domain.com:group/repo.git 端点连接到存储库时如何知道要使用哪个?

Git不知道,还是关心。它只是 运行s ssh。

ssh 是怎么知道的?它查看您的 ~/.ssh/config 文件(编辑:或从 ssh-agent 获取;见下文):

Host github.com
    # IdentitiesOnly yes # see below to decide if you want this
    IdentityFile ~/.ssh/github_id_file

Host domain.com
    IdentitiesOnly yes # again, see below
    IdentityFile ~/.ssh/another_id_file

编辑:这里是link到a Linux version of the ssh_config documentation。虽然每个系统(MacOS、Linux、各种 BSD,甚至 Windows 端口)都有自己的 ssh 配置处理风格,但它们都共享这些可配置项中的大部分。特别注意这两项(我已经为 Whosebug markdown 稍微调整了格式):

IdentitiesOnly

      Specifies that ssh(1) should only use the authentication identity files configured in the ssh_config files, even if ssh-agent(1) or a PKCS11Provider offers more identities. The argument to this keyword must be “yes” or “no”. This option is intended for situations where ssh-agent offers many different identities. The default is “no”.

IdentityFile

      Specifies a file from which the user's DSA, ECDSA, ED25519 or RSA authentication identity is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ed25519 and ~/.ssh/id_rsa for protocol version 2. Additionally, any identities represented by the authentication agent will be used for authentication unless IdentitiesOnly is set. ssh(1) will try to load certificate information from the filename obtained by appending -cert.pub to the path of a specified IdentityFile.

      The file name may use the tilde syntax to refer to a user's home directory or one of the following escape characters: ‘%d’ (local user's home directory), ‘%u’ (local user name), ‘%l’ (local host name), ‘%h’ (remote host name) or ‘%r’ (remote user name).

      It is possible to have multiple identity files specified in configuration files; all these identities will be tried in sequence. Multiple IdentityFile directives will add to the list of identities tried (this behaviour differs from that of other configuration directives).

      IdentityFile may be used in conjunction with IdentitiesOnly to select which identities in an agent are offered during authentication.

一样,IdentityFile 的独特之处在于它是附加的(而不是一个设置覆盖另一个)。

您还可以 运行 ssh(手动)使用额外的 -v 选项来跟踪连接。在 Git 中,您可以将 GIT_SSH 设置为 运行 的脚本的名称 ssh -vvv 以进行临时跟踪(或者对 [=11= 中的日志级别大惊小怪) ] 文件)。我发现这对偶尔调试很有用。 (请注意,您不能通过 GIT_SSH 将选项传递给 ssh,您需要一个单行脚本,例如 ssh-vvv 其中一行为 ssh -vvv $@。)