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

ssh-add ~/.ssh/id_rsa_mynewkey
git clone git@bitbucket.org:mycompany/myrepo.git

其他回答

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

Host github.com
  IdentityFile ~/.ssh/github_rsa

您可以尝试sshmulti-npm包来维护多个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了解更多信息。

在一个命令中克隆

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

您需要创建一个~/.ssh/config,如下所示

Host <Your bitbucket server>
User <userid>
Hostname <Your bitbucket server as above>
IdentitiesOnly yes
IdentityFile ~/.ssh/id_rsa<file> This is your private key file

许可如下

-rw------- $HOME/.ssh/config

将公钥添加到git中(cat~/.ssh/id_rsa_b[或类似名称])

然后是git clone,如下所示

git clone ssh://blahblah@blah.com/userid/test.git