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


当前回答

将该主机或ip添加到.ssh/config文件的更好方法如下:

Host (a space separated list of made up aliases you want to use for the host)
    User git
    Hostname (ip or hostname of git server)
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_(the key you want for this repo)

其他回答

这个方法的问题是,至少在Windows上由bash.exe运行时,它每次都会创建一个新进程,该进程将保持休眠状态。

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

如果您希望按计划将其用于syncig repo,则需要在末尾添加“&&ssh代理-k”。

类似于:

ssh-agent bash -c 'ssh-add C:/Users/user/.ssh/your_key; git -C "C:\Path\to\your\repo" pull && ssh-agent -k' 

ssh代理-k将在完成后终止进程。

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

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

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

此外,作为一个简单的“解决方法”,如果您不经常需要它:

删除所有ssh标识

ssh-add -D

重新添加您需要使用的

ssh-add ~/.ssh/MyProperProfile

做gits

(可选)通过添加其他标识(或所有标识)进行还原。

将该主机或ip添加到.ssh/config文件的更好方法如下:

Host (a space separated list of made up aliases you want to use for the host)
    User git
    Hostname (ip or hostname of git server)
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_(the key you want for this repo)

这是@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。