VSCode:如何通过 ssh 远程连接到远程 WSL2

Mor*_*ort 6 visual-studio-code

是否可以在 VSCode 中编辑远程PC 的WSL2 中的文件。(这就像 Remote-WSL 和 Remote-SSH 的组合。)我可以通过 ssh 和 RDP 连接到那台远程 PC。

该路径\\wsl$\在我的远程 ssh 连接中似乎不可用。

PCA - me, local, VSCode
^
|
ssh and/or RDP
|
V
PCB - remote, WSL2
Run Code Online (Sandbox Code Playgroud)

(我目前在远程 PC 上设置了 Windows OpenSSH,使用默认的 CMD shell。我尝试将 shell 设置为 Bash,但随后无法安装远程扩展。)

更新设置 PC-B 的 ssh 服务器外壳bash.exe 确实解决了我的所有问题。我不确定为什么它以前不起作用。有关更多详细信息,请参阅下面我的回答。

Mor*_*ort 5

回答我自己的问题,我确信我以前试过这个,但没有奏效,但现在我再试一次,它就奏效了。也许我只需要重新启动 Windows 和 WSL2。

  1. 在 PC-B 上启用 Windows SSH 服务器并将 shell 设置为 bash.exe
# Powershell as Administrator
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Set-Service -Name sshd -StartupType 'Automatic'
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\WINDOWS\System32\bash.exe" -PropertyType String -Force
Run Code Online (Sandbox Code Playgroud)
  1. 使用远程 SSH 将 VSCode 从 PC-A 连接到 PC-B(使用 Windows 凭据)并告诉 VSCode 它是一个linux服务器(因为您正在连接到 WSL2 中的 bash.exe)。

    • 如果您使用代理服务器,请将代理添加到您的~/.wgetrc.
  2. 瞧。


这些步骤取自THE EASY WAY how to SSH into Bash and WSL2 on Windows 10 from an external machine where you can find more details.

  • 我找到了那篇博客文章并用同样的方法解决了这个问题!有用! (2认同)

tim*_*mur 4

如果您想连接到远程 WSL,您可能应该将其设置为自己运行,sshd而不是依赖托管 Windows 来进行隧道连接。如果我的问题陈述正确,那么 VS Code 的一篇博客文章中似乎概述了该流程。在这里我将提到我认为您需要达到目标状态的步骤。

首先,在远程Windows上禁用sshd,这样它就不会占用端口22。然后,sshd 在里面 PCB安装并启动:

# from PCB command prompt
# something like that, depending on your choice of distro
sudo apt remove openssh-server && sudo apt install openssh-server
# this would again depend on your chosen distro
sudo /etc/init.d/ssh start # after i do this - windows pops up a firewall prompt to allow me create a rule. you might need to add it manually
Run Code Online (Sandbox Code Playgroud)

那么您需要通过 ssh启用密码登录或(最好生成密钥对并将您的公钥放入/home/your_name/.ssh/authorized_keyson PCB

假设您安装了 OpenSSH for Windows(这似乎是远程 SSH所依赖的客户端),请PCA按照如下所示操作:

# from PCB command prompt
# something like that, depending on your choice of distro
sudo apt remove openssh-server && sudo apt install openssh-server
# this would again depend on your chosen distro
sudo /etc/init.d/ssh start # after i do this - windows pops up a firewall prompt to allow me create a rule. you might need to add it manually
Run Code Online (Sandbox Code Playgroud)

注意权限:ssh 密钥被认为是秘密的,因此除非您删除密钥材料中的所有权限,否则客户端和服务器都不会启动。在 Linux 上执行此操作chmod 600 .ssh/authorized_keys,对于 Windows,请遵循此 SE 答案ssh-agent中的说明。

上面的内容可能看起来有点令人畏惧,但实际上是非常标准的 SSH 设置过程