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

其他回答

2021。如果你在Mac上。

假设你在aws上有一个ubuntu服务器,你通常会这样连接:

% ssh -i blah/yourkeypair.pem ubuntu@test.fattie.com

仅在终端中

% export GIT_SSH_COMMAND="ssh -i /Users/fattie/Desktop/blah/yourkeypair.pem"

在你完成之后。然后你可以自由地。。。

% git clone ubuntu@test.fattie.com:/home/ubuntu/teste.git  

这会将服务器上的repo克隆到本地文件夹“teste”,

然后,在teste/执行通常的命令时,您可以自由地执行。。。

% git push origin master

等等

--

另请注意:https://stackoverflow.com/a/67287133/294884


至于在服务器上,似乎基本上

] git clone --bare the-actual-folder teste.git

然后在teste.git中

] git init --bare --shared

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

文件~/gitwrap.sh

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

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

export GIT_SSH=~/gitwrap.sh

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

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

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

此命令克隆回购并配置SSH密钥以永久使用:

git clone -c "core.sshCommand=ssh -i ~/.ssh/<key>" git@github.com:<user>/<repo>.git

现在,如果运行git fetch、git pull或git push,它将使用core.shCommand中配置的SSH密钥(保存在.git/config中)。

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

整理好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

希望这有帮助。-莱克斯