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字符串对于不同的用户是相同的,这不是问题。)


当前回答

正如其他人提到的,核心。sshCommand config可以覆盖SSH密钥和其他参数。

下面是一个示例,其中有一个名为~/的替代键。Ssh /workrsa,并希望将其用于~/work下克隆的所有存储库。

在~/work下创建一个新的.gitconfig文件:

[core]
  sshCommand = "ssh -i ~/.ssh/workrsa"

在全局git配置中~/。gitconfig,添加:

[includeIf "gitdir:~/work/"]
  path = ~/work/.gitconfig

其他回答

另一种替代方法是使用ssh-ident来管理您的ssh身份。

它会根据您当前的工作目录、ssh选项等自动加载和使用不同的密钥……这意味着您可以轻松地拥有一个工作/目录和一个私有/目录,它们在ssh中透明地使用不同的密钥和身份。

你最多在文件配置键ssh中指定:

# Default GitHub user
Host one
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-one
 IdentitiesOnly yes

#two user
Host two
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-two
 IdentitiesOnly yes

从git 2.10开始,也可以使用gitconfig sshCommand设置。文档状态:

如果设置了这个变量,当git fetch和git push需要连接到远程系统时,它们将使用指定的命令而不是ssh。该命令与GIT_SSH_COMMAND环境变量的形式相同,在设置环境变量时将被覆盖。

一个使用示例是:git config core。ssh -i ~/.ssh/[insert_your_keyname]

在某些情况下,这行不通,因为ssh_config覆盖了命令,在这种情况下,尝试ssh -i ~/。ssh/[insert_your_keyname] -F /dev/null不使用ssh_config. sh

注意:有一种方法可以在之前的回答中应用目录的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。

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

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

解释:

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