这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行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了解更多信息。

其他回答

我使用zsh,不同的密钥会自动加载到我的zsh shell的ssh代理中,用于其他目的(即访问远程服务器)。我修改了@Nick的答案,并将其用于我的一个需要经常刷新的转发。(在本例中,无论我在哪里工作,我都希望在所有计算机上使用相同的最新版本的点文件。)

bash -c 'eval `ssh-agent`; ssh-add /home/myname/.dotfiles/gitread; ssh-add -L; cd /home/myname/.dotfiles && git pull; kill $SSH_AGENT_PID'

生成ssh代理向代理添加只读密钥将目录更改为我的git repo如果cd到repo目录成功,则从远程repo中拉出杀死派生的ssh代理。(我不希望有很多特工在身边徘徊。)

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

文件~/gitwrap.sh

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

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

export GIT_SSH=~/gitwrap.sh

如果这里的其他解决方案都不适合您,并且您已经创建了多个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了解更多信息。

在使用GitBash的Windows中,您可以使用以下方法添加存储库

ssh-agent bash -c 'ssh-add "key-address"; git remote add origin "rep-address"'

例如:

ssh-agent bash -c 'ssh-add /d/test/PrivateKey.ppk; git remote add origin git@git.test.com:test/test.git'

哪个私钥在驱动器D中,计算机的文件夹测试。此外,如果您想克隆存储库,可以使用gitclone更改git远程添加源。

在Git Bash中输入此信息后,它会要求您输入密码!

请注意,openssh私钥和putty私钥是不同的!

如果您使用puttygen创建了密钥,则必须将私钥转换为openssh!

问题是当您在同一主机上有不同的远程存储库(比如github.com),并且您希望使用不同的ssh密钥(即不同的github帐户)与它们进行交互时。

为了做到这一点:

首先,您应该在~/.ssh/config文件中声明不同的密钥。#github.com上常用存储库的密钥主机github.com主机名github.com用户git身份文件~/.ssh/id_rsa#github.com上特定存储库的密钥主机XXX主机名github.com用户git身份文件~/.ssh/id_other_rsa通过这样做,您可以将第二个密钥与github.com的新友好名称“XXX”相关联。然后,您必须更改特定存储库的远程源,以便它使用您刚才定义的友好名称。在命令提示符下转到本地存储库文件夹,并显示当前远程源:>git远程-v起源git@github.com:myuser/myrepo.git(获取)起源git@github.com:myuser/myrepo.git(推送)然后更改原点:>git远程设置url源git@XXX:myuser/myrepo.git>git远程-v起源git@XXX:myuser/myrepo.git(获取)起源git@XXX:myuser/myrepo.git(推送)现在你可以推,取。。。自动按右键。