这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行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 -c core.sshCommand='ssh -i /path/to/key/' clone git@github.com:your_repository.git /path/target/clone --branch git_branch_name

其他回答

为什么不将身份密钥的位置添加到特定回购的git配置文件中,如下所示:

cd .git

vi config

[core]
    sshcommand = ssh -i <IDENTITY_KEY_LOCATION>

这就是你所需要的。

这些解决方案都不适合我。

相反,我详细介绍了@Martin v.Löwis提到的为SSH设置配置文件。

SSH将查找用户的~/.SSH/config文件。我的设置如下:

Host gitserv
    Hostname remote.server.com
    IdentityFile ~/.ssh/id_rsa.github
    IdentitiesOnly yes # see NOTES below

我添加了一个远程git存储库:

git remote add origin git@gitserv:myrepo.git

然后git命令对我来说正常工作。

git push -v origin master

笔记

IdentitesOnly yes是必需的,以防止SSH默认行为发送与每个协议的默认文件名匹配的标识文件。如果您有一个名为~/.ssh/id_rsa的文件,则在不使用此选项的情况下,将在~/.sss/id_rsa.gitub之前尝试该文件。

工具书类

在一个客户端上使用多个SSH私钥的最佳方法我怎样才能阻止ssh提供错误的密钥

在使用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!

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

文件~/gitwrap.sh

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

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

export GIT_SSH=~/gitwrap.sh

其中许多解决方案看起来很诱人。然而,我发现以下链接中的通用git包装脚本方法最有用:

如何使用git命令指定ssh密钥文件

问题是没有git命令,例如:

git -i ~/.ssh/thatuserkey.pem clone thatuser@myserver.com:/git/repo.git

Alvin的解决方案是使用一个定义良好的bash包装器脚本来填补这一空白:

git.sh -i ~/.ssh/thatuserkey.pem clone thatuser@myserver.com:/git/repo.git

其中git.sh为:

#!/bin/bash

# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad
# https://alvinabad.wordpress.com/2013/03/23/how-to-specify-an-ssh-key-file-with-the-git-command

if [ $# -eq 0 ]; then
    echo "Git wrapper script that can specify an ssh-key file
Usage:
    git.sh -i ssh-key-file git-command
    "
    exit 1
fi

# remove temporary file on exit
trap 'rm -f /tmp/.git_ssh.$$' 0

if [ "$1" = "-i" ]; then
    SSH_KEY=$2; shift; shift
    echo "ssh -i $SSH_KEY \$@" > /tmp/.git_ssh.$$
    chmod +x /tmp/.git_ssh.$$
    export GIT_SSH=/tmp/.git_ssh.$$
fi

# in case the git command is repeated
[ "$1" = "git" ] && shift

# Run the git command
git "$@"

我可以验证这是否解决了我在使用git远程更新、git pull和git克隆进行远程比特桶回购时遇到的用户/密钥识别问题;所有这些现在都可以在cron作业脚本中正常工作,否则在有限的shell中导航会遇到困难。我还能够从R中调用这个脚本,并且仍然可以解决完全相同的cron执行问题(例如系统(“bash-git.sh-i~/.ssh/thatuserkey.pem pull”)。

并不是说R和Ruby一样,但如果R能做到这一点…O:-)