这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行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密钥,但仍然无法执行以下简单操作

git pull

那么假设您有两个ssh密钥文件

id_rsa
id_rsa_other_key

然后在git repo中,尝试:

# Run these commands INSIDE your git directory
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_other_key

并通过以下方式确保github默认用户名和userid正确:

# Run these commands INSIDE your git directory
git config user.name "Mona Lisa"
git config user.email "mona.lisa@email.com"

看见https://gist.github.com/jexchan/2351996了解更多信息。

其他回答

my_git_ssh_wrapper的内容:

#!/bin/bash

ssh -i /path/to/ssh/secret/key $1 $2

然后,您可以通过执行以下操作来使用密钥:

GIT_SSH=my_git_ssh_wrapper git clone git@github.com:TheUser/TheProject.git

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

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

此命令克隆回购并配置SSH密钥以永久使用:

git clone -c "core.sshCommand=ssh -i ~/.ssh/<key>" git@github.com:<user>/<repo>.git

现在,如果运行git fetch、git pull或git push,它将使用core.shCommand中配置的SSH密钥(保存在.git/config中)。

这个方法的问题是,至少在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将在完成后终止进程。

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

我认为必须明确强调,如果您通过克隆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

在这里了解更多信息。