也许是一个相当不寻常的情况,但我想指定一个私有 SSH 密钥,以便在从本地计算机执行 shell(git)命令时使用。
基本上是这样的:
git clone [email protected]:TheUser/TheProject.git -key "/home/christoffer/ssh_keys/theuser"甚至更好(在 Ruby 中):
with_key("/home/christoffer/ssh_keys/theuser") do
  sh("git clone [email protected]:TheUser/TheProject.git")
end我见过使用 Net :: SSH 连接到远程服务器的示例,它使用指定的私钥,但这是一个本地命令。可能吗?
这些解决方案都不适合我。
相反,我详细阐述了 @Martinv.Löwis 提到为 SSH 设置config文件。 
 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笔记
IdentitiesOnly yes是防止 SSH 默认行为发送与每个协议的默认文件名匹配的身份文件所必需的。如果您有一个名为~/.ssh/id_rsa的文件,将在没有此选项的~/.ssh/id_rsa.github之前尝试。 参考
这样的东西应该工作(由 orip 建议):
ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'如果您更喜欢子壳,您可以尝试以下(虽然它更脆弱):
ssh-agent $(ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git)Git 将调用 SSH,它将通过环境变量找到它的代理; 反过来,这将加载密钥。
或者,如果您愿意设置仅包含.ssh目录作为HOME的目录,则设置HOME也可以.ssh ; 这可能包含 identity.pub 或配置文件设置 IdentityFile。 
其他人关于~/.ssh/config的建议比较复杂。它可以很简单: 
Host github.com
  IdentityFile ~/.ssh/github_rsa