I have the following use case: I would like to be able to push to git@git.company.com:gitolite-admin using the private key of user gitolite-admin, while I want to push to git@git.company.com:some_repo using 'my own' private key. AFAIK, I can't solve this using ~/.ssh/config, because the user name and server name are identical in both cases. As I mostly use my own private key, I have that defined in ~/.ssh/config for git@git.company.com. Does anyone know of a way to override the key that is used for a single git invocation?

(另外:gitolite根据键来区分谁在进行推送,所以就访问、所有权和审计而言,user@server字符串对于不同的用户是相同的,这不是问题。)


当前回答

如果在windows上使用Git版本的ssh, ssh配置中的身份文件行如下所示

IdentityFile /c/Users/Whoever/.ssh/id_rsa.alice

其中/c代表c:

要检查,在git的bash做

cd ~/.ssh
pwd 

其他回答

要在运行中使用特定的键:

GIT_SSH_COMMAND='ssh -i $HOME/.ssh/id_ed25519 -o IdentitiesOnly=yes -F /dev/null' git push origin c13_training_network

解释:

在执行推送之前,使用本地ENV变量 -i指定键 -F强制配置为空,因此全局配置不会覆盖此临时命令

注意:有一种方法可以在之前的回答中应用目录的git配置,而不仅仅是在回购级别。

在我的例子中,所有的项目都在~/work/目录下,所以我更新了我的gitconfig如下:

# ~/.gitconfig
...

[includeIf "gitdir:~/work/**"]
  path = "~/work/.gitconfig"
# ~/work/.gitconfig
[user]
  email = amr@work.com
  name = Amr Awad
  sshCommand = ssh -i ~/.ssh/work

现在~/work/目录下的所有回购操作都使用工作键~/。Ssh /work,不需要分别配置每个repo。

您可能需要删除(或注释掉)默认的主机配置

如果在windows上使用Git版本的ssh, ssh配置中的身份文件行如下所示

IdentityFile /c/Users/Whoever/.ssh/id_rsa.alice

其中/c代表c:

要检查,在git的bash做

cd ~/.ssh
pwd 

使用~/的一种可能性。ssh/config将使用Match限制而不是Host限制。特别是Match Exec调用shell命令来决定是否应用声明。在bash中,您可以使用以下命令:

[ git@git.company.com:gitolite-admin = $(git config --get remote.origin.url)'' ]

它使用bash[命令来验证两个字符串是否相等。在这种情况下,它正在测试字符串git@git.company.com:gitolite-admin是否与从$(git config——get remote.origin.url) "命令获得的输出匹配。

您可以使用任何其他命令来标识shell所在的存储库。要做到这一点,重要的是在SHELL中定义$SHELL变量,在我的例子中是/bin/bash.完整的示例如下~/.ssh/config:

Match Exec "[ git@git.company.com:gitolite-admin = $(git config --get remote.origin.url)'' ]"
  IdentityFile ~/.ssh/gitolite-admin
  IdentitiesOnly yes
  ForwardAgent no
  ForwardX11 no
  ForwardX11Trusted no

Match Exec "[ git@git.company.com:some_repo = $(git config --get remote.origin.url)'' ]"
  IdentityFile ~/.ssh/yourOwnPrivateKey
  IdentitiesOnly yes
  ForwardAgent no
  ForwardX11 no
  ForwardX11Trusted no

在这个例子中,我假设~/。ssh/yourOwnPrivateKey包含您自己的私钥和~/。Ssh /gitolite-admin包含gitolite-admin用户的私钥。我加入了IdentitiesOnly yes声明,以确保只有一个密钥提供给git服务器,Mark Longair提到过。其他声明只是git的标准ssh选项。

如果您有几个some_repo,想要与不同的键一起使用,您可以添加此配置。如果您在git@git.company.com上有多个存储库,并且大多数存储库使用~/。将此密钥作为主机的默认密钥更有意义。在这种情况下,~/。Ssh /config将是:

Match Exec "[ git@git.company.com:gitolite-admin = $(git config --get remote.origin.url)'' ]"
  IdentityFile ~/.ssh/gitolite-admin
  IdentitiesOnly yes

Host git.company.com
  IdentityFile ~/.ssh/yourOwnPrivateKey
  IdentitiesOnly yes
  ForwardAgent no
  ForwardX11 no
  ForwardX11Trusted no

注意,顺序很重要,Host git.company.com限制应该出现在Match Exec一个或多个限制之后。