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


当前回答

如果SSH端口号不是22(默认值),请在~/.SSH/config中添加端口xx

在我的情况下(同义词),

Host my_synology
    Hostname xxxx.synology.me
    IdentityFile ~/.ssh/id_rsa_xxxx
    User myname
    Port xx

然后使用配置中的主机标题进行克隆。(“my_synology”。避免@chopstik的“*”)

git clone my_synology:path/to/repo.git

其他回答

使用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>'"

对于gitlab RSA认证是

Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/your_private_key_name
  IdentitiesOnly yes

医生来了

这样的方法应该有效(orip建议):

ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone git@github.com:user/project.git'

如果您更喜欢子壳,可以尝试以下方法(尽管它更脆弱):

ssh-agent $(ssh-add /somewhere/yourkey; git clone git@github.com:user/project.git)

Git将调用SSH,SSH将通过环境变量查找其代理;这将反过来加载密钥。

或者,如果您愿意将仅包含.ssh目录的目录设置为HOME,那么设置HOME也可以达到目的;这可能包含identity.pub或配置文件设置IdentityFile。

在一个命令中克隆

git -c core.sshCommand='ssh -i /path/to/key/' clone git@github.com:your_repository.git /path/target/clone --branch git_branch_name

如果这里的其他解决方案都不适合您,并且您已经创建了多个ssh密钥,但仍然无法执行以下简单操作

git pull

那么假设您有两个ssh密钥文件

id_rsa
id_rsa_other_key

然后在git repo中,尝试:

# Run these commands INSIDE your git directory
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_other_key

并通过以下方式确保github默认用户名和userid正确:

# Run these commands INSIDE your git directory
git config user.name "Mona Lisa"
git config user.email "mona.lisa@email.com"

看见https://gist.github.com/jexchan/2351996了解更多信息。