这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行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克隆您的repo:

git-c core.sshCommand=“ssh-i~/.ssh/<your_key>”克隆git@github.com:<user>/<repo>.git

然后cd到克隆的repo中,然后:

git-config-core.shCommand'ssh-i~/.ssh/<your_key>'

要测试它是否工作:

git--git-dir=/path/to/repo/.git pull

所以你可能会想:为什么我在github中安装了.pub,而private在默认目录中之后,我创建的ssh密钥就不起作用了?

该文档为我们提供了一个澄清问题的命令:ssh-vTgit@github.com

输出显示了git查找的ssh密钥列表。因此,您可能希望使用这些名称之一创建密钥,或者使用上述过程来包含所需的密钥。

其他回答

您可以使用GIT_SSH环境变量。但是您需要将ssh和选项打包到shell脚本中。

请参阅命令shell中的git-manual:man-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提供错误的密钥

对于gitlab RSA认证是

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

医生来了

您需要创建一个~/.ssh/config,如下所示

Host <Your bitbucket server>
User <userid>
Hostname <Your bitbucket server as above>
IdentitiesOnly yes
IdentityFile ~/.ssh/id_rsa<file> This is your private key file

许可如下

-rw------- $HOME/.ssh/config

将公钥添加到git中(cat~/.ssh/id_rsa_b[或类似名称])

然后是git clone,如下所示

git clone ssh://blahblah@blah.com/userid/test.git

要使GIT_SSH_COMMAND环境变量在Windows(CMD)下工作,而不是:

set GIT_SSH_COMMAND="ssh -i private_key_file"

Use:

set "GIT_SSH_COMMAND=ssh -i private_key_file"

报价必须是这样的

set "variable=value" 

一些背景:https://stackoverflow.com/a/34402887/10671021