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


当前回答

从Git2.3.0开始,我们还有一个简单的命令(不需要配置文件):

GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git clone user@host:repo.git

请注意,需要-o IdentitesOnly=yes来防止SSH默认行为,即发送与每个协议的默认文件名相匹配的标识文件,如上面的答案所示。

其他回答

在一个命令中克隆

git -c core.sshCommand='ssh -i /path/to/key/' clone git@github.com:your_repository.git /path/target/clone --branch git_branch_name

我使用GIT_SSH环境变量。这是我的包装器,类似于上面的乔·布洛克,但可以处理任何数量的参数。

文件~/gitwrap.sh

#!/bin/bash
ssh -i ~/.ssh/gitkey_rsa "$@"

然后,在my.bashrc中添加以下内容:

export GIT_SSH=~/gitwrap.sh

其他人对~/.ssh/config的建议非常复杂。它可以很简单:

Host github.com
  IdentityFile ~/.ssh/github_rsa

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

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

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

将该主机或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)