这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行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连接到远程服务器的示例,该服务器使用指定的私钥,但这是一个本地命令。有可能吗?


当前回答

my_git_ssh_wrapper的内容:

#!/bin/bash

ssh -i /path/to/ssh/secret/key $1 $2

然后,您可以通过执行以下操作来使用密钥:

GIT_SSH=my_git_ssh_wrapper git clone git@github.com:TheUser/TheProject.git

其他回答

其他人对~/.ssh/config的建议非常复杂。它可以很简单:

Host github.com
  IdentityFile ~/.ssh/github_rsa

使用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 -c core.sshCommand='ssh -i /path/to/key/' clone git@github.com:your_repository.git /path/target/clone --branch git_branch_name

如果您的路径上有要使用给定标识文件签名的目录,则可以通过设置ControlPath,通过.ssh/config文件指定使用特定标识文件,例如:

host github.com
  ControlPath ~/Projects/work/**
  HostName github.com
  IdentityFile ~/.ssh/id_work
  User git

然后,ssh将在给定的工作路径下执行git命令时使用指定的标识文件。

这些解决方案都不适合我。

相反,我详细介绍了@Martin v.Löwis提到的为SSH设置配置文件。

SSH将查找用户的~/.SSH/config文件。我的设置如下:

Host gitserv
    Hostname remote.server.com
    IdentityFile ~/.ssh/id_rsa.github
    IdentitiesOnly yes # see NOTES below

我添加了一个远程git存储库:

git remote add origin git@gitserv:myrepo.git

然后git命令对我来说正常工作。

git push -v origin master

笔记

IdentitesOnly yes是必需的,以防止SSH默认行为发送与每个协议的默认文件名匹配的标识文件。如果您有一个名为~/.ssh/id_rsa的文件,则在不使用此选项的情况下,将在~/.sss/id_rsa.gitub之前尝试该文件。

工具书类

在一个客户端上使用多个SSH私钥的最佳方法我怎样才能阻止ssh提供错误的密钥