首页 > 解决方案 > 如何在 Powershell 中使用 SSH 密钥推送到两个不同的 GitHub 帐户?

问题描述

我在 Windows 10 上,并且安装了适用于 Windows 的 Git。我正在将代码推送到两个不同的 GitHub 帐户,并且我正在尝试将我的 SSH 代理设置为使用两个密钥(每个帐户一个)。

这是我的~\.ssh\config

Host github.com-userone
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa

Host github.com-usertwo
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_usertwo

如果我使用 Git Bash 推/拉它可以正常工作,但我也希望能够使用 Powershell。当我尝试从 Powershell 进行推送或拉取时,我收到“请确保您拥有正确的访问权限”错误。如果我start-ssh-agent.cmd从 Powershell 运行,则git push适用于该 Powershell 实例。

如果我添加start-ssh-agent.cmd到我的profile.ps1配置文件,那么 SSH 代理将启动并git push正常工作,但这似乎破坏了我的 Powershell 配置文件的其他方面(如下所示)。和不再工作Import-ModuleSet-Theme我没有收到任何错误;我只是不再得到我的 posh-git 或 oh-my-git 样式。

Import-Module oh-my-posh
Import-Module posh-git
Set-Theme Paradox
Set-Location "c:\users\brubin\documents\visual studio 2017\projects"
start-ssh-agent.cmd

我发现的大多数让这个工作的指令都涉及运行eval $(ssh-agent -s),但是eval在 Powershell 中不起作用。

如何设置它以便我可以使用 Powershell 从两个不同的 GitHub 帐户推送/拉取?

标签: gitgithub

解决方案


首先,仅当您在创建私钥时使用密码保护了这些私钥时,您才需要 ssh-agent。

其次,确保使用正确的 SSH URL 形式,引用那些 ~/.ssh/config 条目:

github.com-usertwo:<usertwo>/myRepo

dahlbyk/posh-git问题 640所述

我不会使用 Git,而是使用start-ssh-agent.cmdWindows 10 1803 上的内置 OpenSSH。
要使用它,请按照下列步骤操作:

从 PowerShell 窗口运行get-command ssh.exe. 您应该看到它ssh.exe位于C:\Windows\System\OpenSSH\ssh.exe.
如果您没有得到任何结果,请打开 Windows 10 设置应用程序的应用程序和功能部分,然后按“管理可选功能”链接。打开后,选择 OpenSSH 客户端以添加该功能。完成后,再次打开 PowerShell 并查看是否get-command ssh.exe返回C:\Windows\System\OpenSSH\ssh.exe

现在让我们启动 ssh-agent 服务并将其配置为在重新启动时自动启动。
以管理员身份打开 PowerShell 并执行:

Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service

cd 到您$home\.ssh dir并执行ssh-add .\<private-key-file>以将您的私钥文件(和密码)添加到 ssh-agent。
最后一步是让 Git for Windows 使用 WIndows 本机ssh.exe.
为此,请执行:git config --global core.sshCommand C:/WINDOWS/System32/OpenSSH/ssh.exe

而已!现在 ssh-agent 正在运行并为您的密码提供服务。重新启动后它将继续这样做(无需重新输入您的密码)。
更好的是,ssh-agent 将适用于您从“开始”菜单而不是 PowerShell 控制台启动的应用程序(如 Visual Studio)——您必须使用start-ssh-agent.cmd.

笔记:

我在里面输入了“ Services”,Start Menu然后我得到了一个窗口,列出了机器上当前安装的所有服务。
我注意到,在“ OpenSSH Authentication Agent”旁边,它写着“ Stopped”。

我跑了Get-Service ssh-agent | Set-Service -StartupType Manual -PassThru,然后Start-Service ssh-agent它奏效了。
似乎该服务已被禁用或其他什么。我从来没有在 Windows 上接触过这些东西,也许它默认为“已停止”。


推荐阅读