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


当前回答

在使用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环境变量。但是您需要将ssh和选项打包到shell脚本中。

请参阅命令shell中的git-manual:man-git。

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

相反,我详细介绍了@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提供错误的密钥

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

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

下面是我在寻找解决这个问题的方法时发现的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'

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

希望这对你有用。

有很多好答案,但其中一些人假定事先具备管理知识。

我认为必须明确强调,如果您通过克隆web URL开始项目- https://github.com/<用户名>/<项目名称>.git那么您需要确保.git/config中[remote“origin”]下的url值已更改为SSH url(请参见下面的代码块)。

除此之外,请确保添加sshCommand,如下所述:

user@workstation:~/workspace/project-name/.git$ cat config
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = ssh -i ~/location-of/.ssh/private_key -F /dev/null <--Check that this command exist
[remote "origin"]
    url = git@github.com:<user-name>/<project-name>.git  <-- Make sure its the SSH URL and not the WEB URL
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

在这里了解更多信息。