如何使用 Windows 10 的新 OpenSSH 和 PowerShell 维护 ssh-agent 登录会话

如何使用 Windows 10 的新 OpenSSH 和 PowerShell 维护 ssh-agent 登录会话

在我的 Ubuntu 机器上,我仅使用 Keychain 来维护保持登录状态的单个 ssh 代理。

现在 OpenSSH 已内置,我希望 Windows 上也能有类似的东西。我使用 Git Bash 和众所周知的if [ -z "$SSH_AUTH_SOCK" ] ; then ...脚本,但这导致许多 ssh 代理被打开,我知道这是不建议的(部分原因是这篇博文:http://rabexc.org/posts/pitfalls-of-ssh-agents) - 这让我获得了 Ubuntu 的 Keychain。不再使用它的另一个原因是我正在转向使用 PowerShell 作为我的主要 shell。

但我不确定如何在 Windows 上实现同样的事情使用 PowerShell使用 Win32-OpenSSH

谢谢!

答案1

您必须将 OpenSSH 身份验证代理服务配置为自动启动(或者您可以在每次第一次打开 PowerShell 时手动启动它:)Start-Service ssh-agent

之后,你ssh-add C:\path\to\your\ssh\key\id_rsa只需要执行一次。之后每次启动 ssh-agent 时,密钥都会在那里。你可以使用 进行检查ssh-add -l

要让 SSH 代理随 Windows 自动启动,您可以运行:

Set-Service ssh-agent -StartupType Automatic

在管理员 PowerShell 提示符下。

答案2

虽然不是一个完整的答案,但仍然是解决我来这里的问题的方法。 (我还看到另一个人在这里发表的评论,似乎是同样的问题。)

如果您有适用于 Windows 的 Git 或 MinGW 或其他任何可能将 GNU 实用程序添加到 Windows 路径的东西,这可能会干扰适用于 Windows 的 OpenSSH 二进制文件。对我来说,我必须从 PATH 环境变量中删除 ProgramFiles/Git/bin,然后重新启动 PowerShell 才能使其正常工作。在此之前,我收到“与代理通信失败”

答案3

除了这里介绍的内容之外,我在将它与 Git 配合使用时遇到了一个问题,因为 Git 显然默认使用自己的 SSH 可执行文件。要解决这个问题,您需要core.sshCommand在 Git 配置中设置指向 Windows 安装的 OpenSSH 可执行文件:

git config --global core.sshCommand C:/Windows/System32/OpenSSH/ssh.exe

这篇文章是我找到解决方案的地方,它涵盖了在 Windows 中设置 SSH 的所有步骤:https://richardballard.co.uk/ssh-keys-on-windows-10/

答案4

寻找解决方案,ssh-agent在使用的同时保持开放Git Bash(Windows 版 Git 的一部分),而不是 Windows PowerShell,也可能会让你陷入这种境地。下面介绍如何改为使用 Windows PowerShell:

我见过的最好的 Windows 说明在 GitHub 的文档网站上,网址为:https://docs.github.com/en/authentication/connecting-to-github-with-ssh/working-with-ssh-key-passphrases?platform=windows#auto-launching-ssh-agent-on-git-for-windows

本质上,您只需将此脚本添加到 Windows 上的文件底部~/.bashrc(通常在/c/Users/myusername/.bashrc):

# -------------------------------- START -----------------------------------
# Auto-launch the ssh-agent and load all private keys on Git for Windows
# Copied from: https://stackoverflow.com/a/76568760/4561887
env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not
# running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    echo "Starting ssh-agent and adding your private keys."
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    echo "Adding your private keys to ssh-agent."
    ssh-add
fi

unset env
# -------------------------------- END -------------------------------------

我在这里的回答中提供了完整的、适合初学者的说明:Stack Overflow:在 Windows 上启动 Git Bash 时运行 SSH 代理

相关内容