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


当前回答

你可以使用git环境变量GIT_SSH_COMMAND。在你的终端git仓库下运行:

GIT_SSH_COMMAND='ssh -i ~/.ssh/your_private_key' git submodule update --init

取代~ /。Ssh /your_private_key与你想使用的Ssh私钥路径。你可以将后续的git命令(本例中是git子模块update——init)更改为其他命令,如git pull、git fetch等。

其他回答

从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

我在Win7上使用Git Bash。下面的方法对我很有效。

在~/处创建一个配置文件。Ssh /config或c:/users/[your_user_name]/. Ssh /config。在文件中输入:

Host your_host.com
     IdentityFile [absolute_path_to_your_.ssh]\id_rsa

我想主机必须是一个URL,而不仅仅是一个“名称”或参考您的主机。例如,

Host github.com
     IdentityFile c:/users/[user_name]/.ssh/id_rsa

也可以写入“/c/users/[user_name]/....”格式

Giordano Scalzo提供的解决方案也很棒。 https://stackoverflow.com/a/9149518/1738546

使用git config配置您的存储库

git config --add --local core.sshCommand 'ssh -i <<<PATH_TO_SSH_KEY>>>'

这只适用于本地存储库。

你可以使用git环境变量GIT_SSH_COMMAND。在你的终端git仓库下运行:

GIT_SSH_COMMAND='ssh -i ~/.ssh/your_private_key' git submodule update --init

取代~ /。Ssh /your_private_key与你想使用的Ssh私钥路径。你可以将后续的git命令(本例中是git子模块update——init)更改为其他命令,如git pull、git fetch等。

即使用户和主机是相同的,在~/.ssh/config中仍然可以区分它们。例如,如果你的配置是这样的:

Host gitolite-as-alice
  HostName git.company.com
  User git
  IdentityFile /home/whoever/.ssh/id_rsa.alice
  IdentitiesOnly yes

Host gitolite-as-bob
  HostName git.company.com
  User git
  IdentityFile /home/whoever/.ssh/id_dsa.bob
  IdentitiesOnly yes

然后在URL中使用gitolite-as-alice和gitolite-as-bob代替主机名:

git remote add alice git@gitolite-as-alice:whatever.git
git remote add bob git@gitolite-as-bob:whatever.git

Note

您希望包括IdentitiesOnly yes选项,以防止使用默认id。否则,如果您也有与默认名称匹配的id文件,它们将首先被尝试,因为与其他配置选项(遵守“first in wins”)不同,IdentityFile选项附加到要尝试的身份列表中。参见:https://serverfault.com/questions/450796/how-could-i-stop-ssh-offering-a-wrong-key/450807 # 450807