这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行shell(git)命令时要使用的私有SSH密钥。

基本上是这样的:

git clone git@github.com:TheUser/TheProject.git -key "/home/christoffer/ssh_keys/theuser"

或者更好(用Ruby):

with_key("/home/christoffer/ssh_keys/theuser") do
  sh("git clone git@github.com:TheUser/TheProject.git")
end

我见过使用Net::SSH连接到远程服务器的示例,该服务器使用指定的私钥,但这是一个本地命令。有可能吗?


当前回答

我使用GIT_SSH环境变量。这是我的包装器,类似于上面的乔·布洛克,但可以处理任何数量的参数。

文件~/gitwrap.sh

#!/bin/bash
ssh -i ~/.ssh/gitkey_rsa "$@"

然后,在my.bashrc中添加以下内容:

export GIT_SSH=~/gitwrap.sh

其他回答

使用git 2.10+(2016年第三季度:2016年9月2日发布),您可以为git_SSH_COMMAND设置配置(而不仅仅是Rober Jack Will的回答中描述的环境变量)

参见Nguy的承诺书(2016年6月26日)ễn Thái Ng先生ọc杜伊(pclouds)。(2016年7月19日,Junio C Hamano--gitster在提交dc21164中合并)

新的配置变量core.shCommand已添加到指定每个存储库要使用的GIT_SSH_COMMAND值。

core.sshCommand:

如果设置了此变量,gitfetch和gitpush将在需要连接到远程系统时使用指定的命令而不是ssh。该命令的格式与GIT_SSH_command环境变量的格式相同,并且在设置环境变量时被覆盖。

这意味着git pull可以是:

cd /path/to/my/repo/already/cloned
git config core.sshCommand 'ssh -i private_key_file' 
# later on
git pull

您甚至可以只为一个命令(如gitclone)设置它:

git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git

这比设置GIT_SSH_COMMAND环境变量更容易,正如Mátyás Kuti Kreszács所指出的,在Windows上

set "GIT_SSH_COMMAND=ssh -i private_key_file"

对于所有这些命令,可以添加-o IdentitesOnly=yes以将SSH限制为指定的私钥/公钥:

git config core.sshCommand 'ssh -i private_key_file -o IdentitiesOnly=yes' 
# or
git -c core.sshCommand="ssh -i private_key_file -o IdentitiesOnly=yes" clone host:repo.git
# or
set "GIT_SSH_COMMAND=ssh -i private_key_file -o IdentitiesOnly=yes"

gsullins在注释中建议将以下别名添加到.zshrc中:

alias git.key1="git config core.sshCommand 'ssh -i <absolute path to private key>'"
GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone $git_repo

or

export GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key"
git clone REPO
git push

如下所述:https://superuser.com/a/912281/607049

您可以对每个回购进行配置:

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -F /dev/null"
git pull
git push

此外,作为一个简单的“解决方法”,如果您不经常需要它:

删除所有ssh标识

ssh-add -D

重新添加您需要使用的

ssh-add ~/.ssh/MyProperProfile

做gits

(可选)通过添加其他标识(或所有标识)进行还原。

从Git 2.10.0版开始,您可以按回购或全局配置

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -o 'IdentitiesOnly yes'"

这将为当前回购指定ssh密钥将使用的内容。我假设如果您想指定这个全局,只需要设置--global选项。