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

其他回答

从Git 2.10.0版开始,您可以按回购或全局配置

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -o 'IdentitiesOnly yes'"

这将为当前回购指定ssh密钥将使用的内容。我假设如果您想指定这个全局,只需要设置--global选项。

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

将该主机或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)

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

如果SSH端口号不是22(默认值),请在~/.SSH/config中添加端口xx

在我的情况下(同义词),

Host my_synology
    Hostname xxxx.synology.me
    IdentityFile ~/.ssh/id_rsa_xxxx
    User myname
    Port xx

然后使用配置中的主机标题进行克隆。(“my_synology”。避免@chopstik的“*”)

git clone my_synology:path/to/repo.git