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


当前回答

将该主机或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密钥破解:

例如,您有两组不同的键:

键1,键1.pub,键2,键2.pub

将这些密钥保存在.ssh目录中

现在,在.bashrc或.bash_profile别名文件中,添加以下命令

alias key1='cp~/.ssh/key1 id_rsa&&cp~/.ssh/key1.pub id_rsa.pub'

别名key2='cp~/.ssh/key2 id_rsa&&cp~/.ssh/key2.pub id_rsa.pub'

瞧!你有一个快捷方式,可以随时切换按键!

希望这对你有用。

如果你像我一样,你可以:

整理好ssh密钥保持gitclone命令简单为任意数量的存储库处理任意数量的密钥。减少ssh密钥维护。

我将密钥保存在~/.ssh/keys目录中。

我更喜欢约定而不是配置。

我认为守则就是法律;越简单越好。

步骤1-创建别名

将此别名添加到shell:alias git clone='git_SSH=SSH_wrapper git clone'

第2步-创建脚本

将此ssh_wrapper脚本添加到PATH中:

#!/bin/bash
# Filename: ssh_wrapper

if [ -z ${SSH_KEY} ]; then
    SSH_KEY='github.com/l3x'  # <= Default key
fi
SSH_KEY="~/.ssh/keys/${SSH_KEY}/id_rsa"
ssh -i "${SSH_KEY}" "$@"

示例

使用github.com/l3x密钥:

KEY=github.com/l3x git-clone https://github.com/l3x/learn-fp-go

以下示例还使用github.com/l3x密钥(默认情况下):

git-clone https://github.com/l3x/learn-fp-go

使用bitbucket.org/lsheehan密钥:

KEY=bitbucket.org/lsheehan git-clone git@bitbucket.org:dave_andersen/exchange.git

笔记

将SSH_wrapper脚本中的默认SSH_KEY更改为大多数时间使用的SSH_KEY。这样,您不需要在大多数时间使用KEY变量。

你可能会想,“嘿!别名、脚本和一些密钥目录都是如此,”但对我来说,这是惯例。我几乎所有的工作站(以及服务器)都是类似的配置。

我的目标是简化我定期执行的命令。

我的约定,例如Bash脚本、别名等,创建了一个一致的环境,并帮助我保持简单。

KISS和名字很重要。

有关更多设计技巧,请参阅我的书《Go》中的第4章固体设计:https://www.amazon.com/Learning-Functional-Programming-Lex-Sheehan-ebook/dp/B0725B8MYW

希望这有帮助。-莱克斯

将该主机或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/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选项。