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

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

键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'

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

希望这对你有用。

其他回答

其中许多解决方案看起来很诱人。然而,我发现以下链接中的通用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 2.10.0版开始,您可以按回购或全局配置

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

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

此外,作为一个简单的“解决方法”,如果您不经常需要它:

删除所有ssh标识

ssh-add -D

重新添加您需要使用的

ssh-add ~/.ssh/MyProperProfile

做gits

(可选)通过添加其他标识(或所有标识)进行还原。

问题是当您在同一主机上有不同的远程存储库(比如github.com),并且您希望使用不同的ssh密钥(即不同的github帐户)与它们进行交互时。

为了做到这一点:

首先,您应该在~/.ssh/config文件中声明不同的密钥。#github.com上常用存储库的密钥主机github.com主机名github.com用户git身份文件~/.ssh/id_rsa#github.com上特定存储库的密钥主机XXX主机名github.com用户git身份文件~/.ssh/id_other_rsa通过这样做,您可以将第二个密钥与github.com的新友好名称“XXX”相关联。然后,您必须更改特定存储库的远程源,以便它使用您刚才定义的友好名称。在命令提示符下转到本地存储库文件夹,并显示当前远程源:>git远程-v起源git@github.com:myuser/myrepo.git(获取)起源git@github.com:myuser/myrepo.git(推送)然后更改原点:>git远程设置url源git@XXX:myuser/myrepo.git>git远程-v起源git@XXX:myuser/myrepo.git(获取)起源git@XXX:myuser/myrepo.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)