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


当前回答

如果您的路径上有要使用给定标识文件签名的目录,则可以通过设置ControlPath,通过.ssh/config文件指定使用特定标识文件,例如:

host github.com
  ControlPath ~/Projects/work/**
  HostName github.com
  IdentityFile ~/.ssh/id_work
  User git

然后,ssh将在给定的工作路径下执行git命令时使用指定的标识文件。

其他回答

这是@VonC答案的扩展。请先阅读。

用例是我需要使用SSH同时使用个人和工作GitHub帐户。我希望使用工作SSH密钥作为默认值,因为我的项目内部将有其他工作repo作为依赖项。因此克隆它们应该可以无缝工作。

我遵循的步骤是:

生成默认SSH密钥并将其添加到工作git帐户。在单独的文件中生成个人SSH密钥,并将其添加到个人git帐户。在.bashrc或.zshrc文件中添加以下函数代码并将其作为源代码。gclone(){#使用个人ssh密钥克隆回购urlgit-c core.sshCommand=“ssh-i path_to_personal_key”clone“$1”&&#使用“awk”从URL提取回购名称,并使用“cd”切换到该文件夹cd$(awk‘{sub(/.*\//,“”);sub(/\.git.*/,“””);print}‘<<“$1”)&&#将个人ssh密钥设置为此回购的默认密钥git-config-core.shCommand“ssh-i path_to_personal_key”;}使用gclone命令使用个人SSH密钥克隆repo,并将repo设置为默认使用该密钥。使用正常的gitclone命令以默认(工作)SSH密钥克隆repo。

GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone $git_repo

or

export GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key"
git clone REPO
git push

其中许多解决方案看起来很诱人。然而,我发现以下链接中的通用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:-)

当您需要使用普通请求(git pull origin master)连接到github时,在~/.ssh/config中将主机设置为*对我有效,但其他任何主机(例如“github”或“gb”)都不起作用。

Host *
    User git
    Hostname github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_xxx

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