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


当前回答

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

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

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

其他回答

对于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_SSH环境变量。但是您需要将ssh和选项打包到shell脚本中。

请参阅命令shell中的git-manual:man-git。

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

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

相反,我详细介绍了@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提供错误的密钥