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


当前回答

有很多好答案,但其中一些人假定事先具备管理知识。

我认为必须明确强调,如果您通过克隆web URL开始项目- https://github.com/<用户名>/<项目名称>.git那么您需要确保.git/config中[remote“origin”]下的url值已更改为SSH url(请参见下面的代码块)。

除此之外,请确保添加sshCommand,如下所述:

user@workstation:~/workspace/project-name/.git$ cat config
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = ssh -i ~/location-of/.ssh/private_key -F /dev/null <--Check that this command exist
[remote "origin"]
    url = git@github.com:<user-name>/<project-name>.git  <-- Make sure its the SSH URL and not the WEB URL
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

在这里了解更多信息。

其他回答

最快、最简单的方法是:

使用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密钥列表。因此,您可能希望使用这些名称之一创建密钥,或者使用上述过程来包含所需的密钥。

这是@VonC答案的扩展。请先阅读。

用例是我需要使用SSH同时使用个人和工作GitHub帐户。我希望使用工作SSH密钥作为默认值,因为我的项目内部将有其他工作repo作为依赖项。因此克隆它们应该可以无缝工作。

我遵循的步骤是:

生成默认SSH密钥并将其添加到工作git帐户。在单独的文件中生成个人SSH密钥,并将其添加到个人git帐户。在.bashrc或.zshrc文件中添加以下函数代码并将其作为源代码。gclone(){#使用个人ssh密钥克隆回购urlgit-c core.sshCommand=“ssh-i path_to_personal_key”clone“$1”&&#使用“awk”从URL提取回购名称,并使用“cd”切换到该文件夹cd$(awk‘{sub(/.*\//,“”);sub(/\.git.*/,“””);print}‘<<“$1”)&&#将个人ssh密钥设置为此回购的默认密钥git-config-core.shCommand“ssh-i path_to_personal_key”;}使用gclone命令使用个人SSH密钥克隆repo,并将repo设置为默认使用该密钥。使用正常的gitclone命令以默认(工作)SSH密钥克隆repo。

从Git 2.10.0版开始,您可以按回购或全局配置

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -o 'IdentitiesOnly yes'"

这将为当前回购指定ssh密钥将使用的内容。我假设如果您想指定这个全局,只需要设置--global选项。

对于gitlab RSA认证是

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

医生来了

我只需要添加密钥,然后再次运行git克隆。

ssh-add ~/.ssh/id_rsa_mynewkey
git clone git@bitbucket.org:mycompany/myrepo.git