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


当前回答

如下所述:https://superuser.com/a/912281/607049

您可以对每个回购进行配置:

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -F /dev/null"
git pull
git push

其他回答

总结一下答案和评论,设置git以使用不同的密钥文件,然后忘记它的最佳方法是编辑~/.ssh/config(或c:\users\<youruser>\.ssh\config)并指定多个身份,这也支持同一主机的不同用户(例如,个人GitHub帐户和工作用户),这也适用于Windows:

Host github.com
HostName github.com
IdentityFile /path/to/your/personal/github/private/key
User dandv

Host github-work
HostName github.com
IdentityFile /path/to/your/work/github/private/key
User workuser

然后,要将项目克隆为您的个人用户,只需运行常规gitclone命令即可。

要将repo克隆为工作用户,请运行gitclonegit@github-work:公司/项目.git。

下面是我在寻找解决这个问题的方法时发现的ssh密钥破解:

例如,您有两组不同的键:

键1,键1.pub,键2,键2.pub

将这些密钥保存在.ssh目录中

现在,在.bashrc或.bash_profile别名文件中,添加以下命令

alias key1='cp~/.ssh/key1 id_rsa&&cp~/.ssh/key1.pub id_rsa.pub'

别名key2='cp~/.ssh/key2 id_rsa&&cp~/.ssh/key2.pub id_rsa.pub'

瞧!你有一个快捷方式,可以随时切换按键!

希望这对你有用。

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

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

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

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

请参阅命令shell中的git-manual:man-git。

在一个命令中克隆

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