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


当前回答

当您需要使用普通请求(git pull origin master)连接到github时,在~/.ssh/config中将主机设置为*对我有效,但其他任何主机(例如“github”或“gb”)都不起作用。

Host *
    User git
    Hostname github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_xxx

其他回答

这个方法的问题是,至少在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克隆。

ssh-add ~/.ssh/id_rsa_mynewkey
git clone git@bitbucket.org:mycompany/myrepo.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)

当您需要使用普通请求(git pull origin master)连接到github时,在~/.ssh/config中将主机设置为*对我有效,但其他任何主机(例如“github”或“gb”)都不起作用。

Host *
    User git
    Hostname github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_xxx

使用git 2.10+(2016年第三季度:2016年9月2日发布),您可以为git_SSH_COMMAND设置配置(而不仅仅是Rober Jack Will的回答中描述的环境变量)

参见Nguy的承诺书(2016年6月26日)ễn Thái Ng先生ọc杜伊(pclouds)。(2016年7月19日,Junio C Hamano--gitster在提交dc21164中合并)

新的配置变量core.shCommand已添加到指定每个存储库要使用的GIT_SSH_COMMAND值。

core.sshCommand:

如果设置了此变量,gitfetch和gitpush将在需要连接到远程系统时使用指定的命令而不是ssh。该命令的格式与GIT_SSH_command环境变量的格式相同,并且在设置环境变量时被覆盖。

这意味着git pull可以是:

cd /path/to/my/repo/already/cloned
git config core.sshCommand 'ssh -i private_key_file' 
# later on
git pull

您甚至可以只为一个命令(如gitclone)设置它:

git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git

这比设置GIT_SSH_COMMAND环境变量更容易,正如Mátyás Kuti Kreszács所指出的,在Windows上

set "GIT_SSH_COMMAND=ssh -i private_key_file"

对于所有这些命令,可以添加-o IdentitesOnly=yes以将SSH限制为指定的私钥/公钥:

git config core.sshCommand 'ssh -i private_key_file -o IdentitiesOnly=yes' 
# or
git -c core.sshCommand="ssh -i private_key_file -o IdentitiesOnly=yes" clone host:repo.git
# or
set "GIT_SSH_COMMAND=ssh -i private_key_file -o IdentitiesOnly=yes"

gsullins在注释中建议将以下别名添加到.zshrc中:

alias git.key1="git config core.sshCommand 'ssh -i <absolute path to private key>'"