Skip to content

Instantly share code, notes, and snippets.

@mattbell87
Last active June 16, 2024 19:30
Show Gist options
  • Save mattbell87/f5bd7b78c8d0ad7f0dfc3addae4f4897 to your computer and use it in GitHub Desktop.
Save mattbell87/f5bd7b78c8d0ad7f0dfc3addae4f4897 to your computer and use it in GitHub Desktop.
VSCode Remote: Connect to WSL2 from another machine

VSCode Remote: Connect to WSL2 from another machine

Do you want to do remote development on your WSL2 container in Visual Studio Code? Read this.

Proxy jump method

  1. On the host set up OpenSSH for Windows
  2. Run wsl --update to make sure you are running the latest WSL
  3. Open WSL and install another SSH server inside WSL with sudo apt-get install openssh-server
  4. Now run sudo systemctl enable --now ssh to automatically start ssh when WSL starts.
  5. On the remote machine run ssh -J windows_user@windows_ip wsl_user@localhost to see if the proxy jump will work

If you see the bash prompt it works. You can add it to the ~/.ssh/config file on the remote machine.

Host remote-wsl
  HostName localhost
  User wsl_user
  ProxyJump windows_user@windows_ip
  StrictHostKeyChecking no

Now connect with ssh remote-wsl.

Credit

ajihyf's comment

Default shell method

Change your OpenSSH shell

SSH to your Windows host (SSH Server must be installed in Windows Features)

ssh user@windowshost

Start Powershell

powershell

Run this command to switch SSH from CMD to WSL

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\WINDOWS\System32\bash.exe" -PropertyType String -Force

Test

ssh user@windowshost

You should now see WSL2 instead of CMD

Connect from VSCode

At this point you can connect to your Win10 host with Remote SSH in VSCode with your Windows username and pw. But you'll actually start and connect to WSL2.

  1. Install the Remote - SSH extension
  2. Add a new SSH target and connect with your Windows host, username and password (you will automatically log in as the Linux user)

Credit

The workaround was inspired by: https://www.hanselman.com/blog/the-easy-way-how-to-ssh-into-bash-and-wsl2-on-windows-10-from-an-external-machine

@mattbell87
Copy link
Author

Hello @mattbell87,

I owe you for saving so much of my time, Thank you.

However, Let me know if you can help me with this. I use ZSH as my default shell on my main WSL computer, and I would also like to replicate this remotely.

I am looking as we speak, but leaving this here in case you have any pointers. I will ofcourse check back if I find a solution.

Cheers.

EDIT: I have resorted to just doing zsh as the terminal opens for now. But I will definitely update once I find an automated solution as I need to spend my brain juice on development more atm :)

Hey @themegabyte I haven't tested this but you could try the second part of the guide with wsl.exe instead of bash.exe. So:

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\WINDOWS\System32\wsl.exe" -PropertyType String -Force

@alexandremendoncaalvaro
Copy link

Hello @mattbell87,
I owe you for saving so much of my time, Thank you.
However, Let me know if you can help me with this. I use ZSH as my default shell on my main WSL computer, and I would also like to replicate this remotely.
I am looking as we speak, but leaving this here in case you have any pointers. I will ofcourse check back if I find a solution.
Cheers.
EDIT: I have resorted to just doing zsh as the terminal opens for now. But I will definitely update once I find an automated solution as I need to spend my brain juice on development more atm :)

Hey @themegabyte I haven't tested this but you could try the second part of the guide with wsl.exe instead of bash.exe. So:

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\WINDOWS\System32\wsl.exe" -PropertyType String -Force

It worked like a charm!

@mckamyk
Copy link

mckamyk commented Jun 28, 2022

This looks like the solution I'm needing right now.

Not familiar with this level of registry stuff in windows. Does this persist across reboots?

Is there a way to still access CMD, either externally via SSH or internally from the WSL instance, should I need it? I occasionally will need to run commands from CMD in windows in my development work.

@mattbell87
Copy link
Author

This looks like the solution I'm needing right now.

Not familiar with this level of registry stuff in windows. Does this persist across reboots?

Is there a way to still access CMD, either externally via SSH or internally from the WSL instance, should I need it? I occasionally will need to run commands from CMD in windows in my development work.

It does persist across reboots and you can access Windows programs from WSL, eg if your type powershell.exe you'll get a PowerShell prompt.

@mckamyk
Copy link

mckamyk commented Jun 28, 2022

This looks like the solution I'm needing right now.
Not familiar with this level of registry stuff in windows. Does this persist across reboots?
Is there a way to still access CMD, either externally via SSH or internally from the WSL instance, should I need it? I occasionally will need to run commands from CMD in windows in my development work.

It does persist across reboots and you can access Windows programs from WSL, eg if your type powershell.exe you'll get a PowerShell prompt.

Well, I ended up trying it out, but I'm not sure its what I want. Because Windows's SSH daemon is whats brokering the VSCode client, the file system scope is from Window's FS. I've a lots of performance issues running linux binaries on Window's FS, because its translating through a some kind of quasi-network share between the Linux VM and Windows FS. When connected this way, I'm not able to mount VSCode on folders that are inside the Linux VM it appears.

I'm setting up an SSH tunnel from my remote machine, where the tunnel has windows point to the Linux's SSH server, and VS code is connecting to that.

# the -t argument dumps you into default shell on default distro
ssh winUser@winIp -t "C:\Windows\System32\wsl.exe"
# to get IP of VM, e.g. 172.18.222.18
ip a
# make sure sshd is started, listening on non-22. e.g. 2222
sudo /usr/sbin/sshd -D

# back on the local machine, leave this running...
ssh winUser@winIp -L 2244:172.18.222.18:2222

# use this as the SSH command on the Remote - SSH host config
ssh wslUser@localhost -p 2244

This way VSCode is mounted inside the VM natively with better IO performance.

@q815101630
Copy link

One small issue I faced is that when I connected to a Windows host and applied the command, it will not immediately work because VScode would still try to connect to a Windows Powershell next time.
What I did is delete the corresponding remote.SSH.remotePlatform entry in the user setting file. Now it works. Thank you

@vbrozik
Copy link

vbrozik commented Oct 6, 2022

In this AskUbuntu answer Access WSL2 Ubuntu's application on hosted machine's network there is a nice solution how to make a TCP port from WSL2 accessible over network. You can run a ssh daemon inside WSL2, make it accessible and connect over SSH as to a usual Linux machine.

It does not need the additional unnecessary SSH encryption and running sshd on the Windows host. It uses a simple TCP proxy netsh interface portproxy.

wsl_win_proxy() {
    wsl_ip="$(ip route | grep -oP '^.*src \K[0-9\.]+')"
    wsl_port="8080"

    win_ip="0.0.0.0"
    win_port="8080"

    rule_name="Inbound TCP ${win_port}"
    win_get_fw_rule_cmd="Get-NetFirewallRule | Where { \$_.DisplayName -eq '${rule_name}' }"
    win_new_fw_rule_cmd="New-NetFirewallRule -DisplayName '${rule_name}' -Direction Inbound -Action Allow -Protocol TCP -LocalPort ${win_port}"

    if ! netsh.exe interface portproxy show all | grep -q -P "${win_ip}\s+${win_port}\s+${wsl_ip}\s+${wsl_port}"
    then
        powershell.exe Start-Process -Verb runAs -FilePath "netsh.exe" \
            -ArgumentList "interface","portproxy","add","v4tov4",\
                    "listenport=$win_port","listenaddress=$win_ip",\
                    "connectport=$wsl_port","connectaddress=$wsl_ip"

        if [[ $? -eq 0 ]]
        then
            echo "Port proxy '${win_ip}:${win_port} > ${wsl_ip}:${wsl_port}' is created."
        else
            echo "Port proxy '${win_ip}:${win_port} > ${wsl_ip}:${wsl_port}' failed."
        fi

        if ! powershell.exe ${win_get_fw_rule_cmd} | grep -q "$rule_name"
        then
            echo "Open PowerShell as Admin and create the following firewall rule:"
            echo -e '\033[1;33m'"$win_new_fw_rule_cmd"'\033[0m'
        fi
    fi
}
wsl_win_proxy

@awohaoa
Copy link

awohaoa commented Oct 22, 2022

I'm only able to use this to remote in once: after that, subsequent connection attempts result in The file cannot be accessed by the system. Connection to [local IP address] closed. until I reboot the Windows host. I can't connect with VSCode SSH Remote at all.

@jimjam-slam I have the same problem as one, did you solve it?

@awohaoa
Copy link

awohaoa commented Oct 22, 2022

Hello @mattbell87,
I'm having a problem with ssh connections, but I'm not sure what's causing it.
Here is my connection log

C:\Users\mems>ssh -v mems@192.168.1.72
OpenSSH_for_Windows_8.6p1, LibreSSL 3.4.3
debug1: Reading configuration data C:\\Users\\mems/.ssh/config
debug1: C:\\Users\\mems/.ssh/config line 1: Applying options for 192.168.1.72
debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling
debug1: Connecting to 192.168.1.72 [192.168.1.72] port 22.
debug1: Connection established.
debug1: identity file C:\\Users\\mems/.ssh/id_rsa type -1
debug1: identity file C:\\Users\\mems/.ssh/id_rsa-cert type -1
debug1: identity file C:\\Users\\mems/.ssh/id_dsa type -1
debug1: identity file C:\\Users\\mems/.ssh/id_dsa-cert type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ecdsa type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ecdsa-cert type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ecdsa_sk type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ed25519 type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ed25519-cert type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ed25519_sk type -1
debug1: identity file C:\\Users\\mems/.ssh/id_ed25519_sk-cert type -1
debug1: identity file C:\\Users\\mems/.ssh/id_xmss type -1
debug1: identity file C:\\Users\\mems/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_for_Windows_8.6
debug1: Remote protocol version 2.0, remote software version OpenSSH_for_Windows_8.6
debug1: compat_banner: match: OpenSSH_for_Windows_8.6 pat OpenSSH* compat 0x04000000
debug1: Authenticating to 192.168.1.72:22 as 'mems'
debug1: load_hostkeys: fopen C:\\Users\\mems/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen __PROGRAMDATA__\\ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen __PROGRAMDATA__\\ssh/ssh_known_hosts2: No such file or directory
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ssh-ed25519
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: SSH2_MSG_KEX_ECDH_REPLY received
debug1: Server host key: ssh-ed25519 SHA256:9YTeeXvvXZv+IRjWZ5VFdzJ9R4NkEeXbqrJWe6lnEQo
debug1: load_hostkeys: fopen C:\\Users\\mems/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen __PROGRAMDATA__\\ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen __PROGRAMDATA__\\ssh/ssh_known_hosts2: No such file or directory
debug1: Host '192.168.1.72' is known and matches the ED25519 host key.
debug1: Found key in C:\\Users\\mems/.ssh/known_hosts:1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: pubkey_prepare: ssh_get_authentication_socket: No such file or directory
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_rsa
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_dsa
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_ecdsa
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_ecdsa_sk
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_ed25519
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_ed25519_sk
debug1: Will attempt key: C:\\Users\\mems/.ssh/id_xmss
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,sk-ssh-ed25519@openssh.com,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,webauthn-sk-ecdsa-sha2-nistp256@openssh.com>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Trying private key: C:\\Users\\mems/.ssh/id_rsa
debug1: Trying private key: C:\\Users\\mems/.ssh/id_dsa
debug1: Trying private key: C:\\Users\\mems/.ssh/id_ecdsa
debug1: Trying private key: C:\\Users\\mems/.ssh/id_ecdsa_sk
debug1: Trying private key: C:\\Users\\mems/.ssh/id_ed25519
debug1: Trying private key: C:\\Users\\mems/.ssh/id_ed25519_sk
debug1: Trying private key: C:\\Users\\mems/.ssh/id_xmss
debug1: Next authentication method: keyboard-interactive
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: password
mems@192.168.1.72's password:
debug1: Authentication succeeded (password).
Authenticated to 192.168.1.72 ([192.168.1.72]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: filesystem full
debug1: ENABLE_VIRTUAL_TERMINAL_INPUT is supported. Reading the VTSequence from console
debug1: ENABLE_VIRTUAL_TERMINAL_PROCESSING is supported. Console supports the ansi parsing
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: client_input_hostkeys: searching C:\\Users\\mems/.ssh/known_hosts for 192.168.1.72 / (none)
debug1: client_input_hostkeys: searching C:\\Users\\mems/.ssh/known_hosts2 for 192.168.1.72 / (none)
debug1: client_input_hostkeys: hostkeys file C:\\Users\\mems/.ssh/known_hosts2 does not exist
debug1: client_input_hostkeys: no new or deprecated keys from server
debug1: ssh_get_authentication_socket: No such file or directory
The file cannot be accessed by the system.
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
debug1: channel 0: free: client-session, nchannels 1
Connection to 192.168.1.72 closed.
Transferred: sent 2032, received 2688 bytes, in 0.1 seconds
Bytes per second: sent 25999.3, received 34392.8
debug1: Exit status 0

@mattbell87
Copy link
Author

@awohaoa looks like it is authenticating correctly, but it's not running your default shell correctly. Maybe open regedit and go to HKLM\SOFTWARE\OpenSSH, make sure the app in DefaultShell is something that runs and stays open.

@awohaoa
Copy link

awohaoa commented Oct 23, 2022

@awohaoa looks like it is authenticating correctly, but it's not running your default shell correctly. Maybe open regedit and go to HKLM\SOFTWARE\OpenSSH, make sure the app in DefaultShell is something that runs and stays open.

Hi ,@mattbell87
I have checked regedit and I found that I have set the default shell to bash.
20221023130639
But I found that it still calls cmd.exe instead of bash

[12:52:03.686] SSH Resolver called for "ssh-remote+192.168.1.72", attempt 5, (Reconnection)
[12:52:03.687] SSH Resolver called for host: 192.168.1.72
[12:52:03.688] Setting up SSH remote "192.168.1.72"
[12:52:03.689] Using commit id "fad3a77833b9249158dfd88477114a06435e46a2" and quality "insider" for server
[12:52:03.691] Install and start server if needed
[12:52:07.269] Running script with connection command: ssh -T -D 58369 "192.168.1.72" bash
[12:52:07.271] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[12:52:08.399] > mems@192.168.1.72's password:οΏ½]0;C:\WINDOWS\System32\cmd.exeοΏ½
[12:52:08.399] Got some output, clearing connection timeout
[12:52:08.400] Showing password prompt

By the way,here is my wsl2 version information, I am not sure if it is related to this version

PS C:\Users\mems> wsl.exe --version
WSL Version: 0.70.0.0
Kernel Version: 5.15.68.1
WSLg Version: 1.0.45
MSRDC Version: 1.2.3575
Direct3D Version: 1.606.4
DXCore Version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
WindowsVersion: 10.0.22621.674

@joelhampe
Copy link

I'm only able to use this to remote in once: after that, subsequent connection attempts result in The file cannot be accessed by the system. Connection to [local IP address] closed. until I reboot the Windows host. I can't connect with VSCode SSH Remote at all.

@jimjam-slam I have the same problem as one, did you solve it?

I started seeing this as well. Turns out it was from upgrading to WSL in the MSFT store. As noted here there is a known issue with that version and the fix is to uninstall the store version. That fixed it for me.

https://superuser.com/questions/1714736/cannot-run-wsl2-over-ssh-on-windows-11

@FarisHijazi
Copy link

I'm only able to use this to remote in once: after that, subsequent connection attempts result in The file cannot be accessed by the system. Connection to [local IP address] closed. until I reboot the Windows host. I can't connect with VSCode SSH Remote at all.

@jimjam-slam I have the same problem as one, did you solve it?

I started seeing this as well. Turns out it was from upgrading to WSL in the MSFT store. As noted here there is a known issue with that version and the fix is to uninstall the store version. That fixed it for me.

https://superuser.com/questions/1714736/cannot-run-wsl2-over-ssh-on-windows-11

THANK YOU!! this is what I was looking for

@JeffreyLin39
Copy link

Thank you πŸ™πŸ™πŸ™

@thelastfantasy
Copy link

Maybe need to run this command after OpenSSH Server installed (with Administrator Command Prompt).
net start sshd

@sungkim11
Copy link

I came to a realization that the only way to do this reliably is via the use of third party services like Tailscale.

@okamototomoyuki
Copy link

I am being repeatedly prompted to enter a password in VSCode.
Each time I input it, the following message appears.
What can I do to resolve this issue?

[18:02:36.830] Got password response
[18:02:36.830] "install" wrote data to terminal: "**********"
[18:02:36.883] > 
> 
[18:02:37.446] > c87f957e6d36: running
> Acquiring lock on /home/MYUSER/.vscode-server/bin/784b0177c56c607789f9638da7b
> 6bf3230d47a8c/vscode-remote-lock.MYUSER.784b0177c56c607789f9638da7b6bf3230d47
> a8c
> Installation already in progress...
> If you continue to see this message, you can try toggling the remote.SSH.useFloc
> k setting
> c87f957e6d36: start
> exitCode==24==
> listeningOn====
> osReleaseId==ubuntu==
> arch==x86_64==
> tmpDir==/tmp==
> platform==linux==
> unpackResult====
> didLocalDownload==0==
> downloadTime====
> installTime====
> extInstallTime====
> serverStartTime====
> c87f957e6d36: end
> 
[18:02:37.446] Received install output: 
exitCode==24==
listeningOn====
osReleaseId==ubuntu==
arch==x86_64==
tmpDir==/tmp==
platform==linux==
unpackResult====
didLocalDownload==0==
downloadTime====
installTime====
extInstallTime====
serverStartTime====

[18:02:37.446] Server installation process already in progress - waiting and retrying
[18:02:37.765] "install" terminal command done
[18:02:37.766] Install terminal quit with output: 
[18:02:38.453] Running script with connection command: ssh -T -D 54675 "IPADDRESS" bash
[18:02:38.461] Terminal shell path: C:\Windows\System32\cmd.exe
[18:02:38.905] > 
[18:02:38.905] Got some output, clearing connection timeout
[18:02:39.470] > MYUSER@IPADDRESS's password:
[18:02:39.470] Showing password prompt

@okamototomoyuki
Copy link

[18:02:37.446] Server installation process already in progress - waiting and retrying
[18:02:37.765] "install" terminal command done
[18:02:37.766] Install terminal quit with output: 
[18:02:38.453] Running script with connection command: ssh -T -D 54675 "IPADDRESS" bash
[18:02:38.461] Terminal shell path: C:\Windows\System32\cmd.exe
[18:02:38.905] > 
[18:02:38.905] Got some output, clearing connection timeout
[18:02:39.470] > MYUSER@IPADDRESS's password:
[18:02:39.470] Showing password prompt

I apologize, this error was resolved by deleting the '.vscode-server' folder.
However, it does not work after the following command.
Does anyone know what the problem is?

[09:07:37.119] > scp: /home/MYUSER/.vscode-server/bin/784b0177c56c607789f9638da7b6bf3230d47a8c
> : No such file or directory
> 
[09:07:37.455] "Copy server to host" terminal command done
[09:07:38.464] > 
[09:07:41.399] > 
[09:07:44.481] > 
[09:07:47.551] > 
[09:07:50.622] > 
[09:07:53.402] > 

@astanziola
Copy link

Hi everyone! I've got all the tricks in place and I can open the wsl form remote.

By the way, if someone still gets the "Access is denied" problem when trying to open the wsl from an ssh session, this worked for me: microsoft/WSL#4920 (comment)

However, when I try to connect the remote extension it doesn't manage to connect to the remote machine. It connects instead if the default terminal is cmd or powershell, rather than wsl / bash.

Has anyone encountered a similar problem?

Interestingly, before connecting, the remote extension doesn't ask if the system is a Windows or Linux machine, so perhaps it assumes is Windows and then somehow fails because it finds another terminal?

@elfmimi
Copy link

elfmimi commented Mar 21, 2023

I'm not yet fully convinced myself, but you only need to change remote.SSH.remotePlatform for your Windows host to Linux.
What I mean is that you don't have to change DefaultShell .
Then Remote-SSH will recognize the situation and automatically launches wsl before making handshake with vscode-server.
Then Remote-SSH will connect to Windows host with something like ssh -t {hostname} bash . This will effectively launch wsl by executing C:\Windows\System32\bash.exe .
At least that it how I understand it. You may also need WSL extension installed, not sure.
You need either of wget or curl installed in your wsl env.

@jorlow
Copy link

jorlow commented Jul 13, 2023

I got access denied. Instead I just ran openssh within wsl2 on port 2222 and did this from within powershell.

netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=2222 connectaddress=127.0.0.1 connectport=2222

I then just ssh to port 2222 and it's forwarded to the wsl2 version of openssh.

@ajihyf
Copy link

ajihyf commented Nov 16, 2023

Latest WSL2 has systemctl support and can automatically map sshd's connection to the Windows host. No need to redirect port.

  1. Make sure Windows OpenSSH works.
  2. In windows, run wsl --update to make sure use latest WSL.
  3. In WSL, run sudo apt-get install openssh-server to install ssh and sudo systemctl enable --now ssh to automatically start ssh when WSL starts.
  4. Run ssh -J windows_user@windows_ip wsl_user@localhost to login to ssh
  5. If step 4 works, add the following content to .ssh/config
Host wsl
  HostName localhost
  User wsl_user
  ProxyJump windows_user@windows_ip
  StrictHostKeyChecking no
  UserKnownHostsFile=/dev/null
  1. Connect to wsl remote in VSCode πŸŽ‰πŸŽ‰πŸŽ‰

@flackend
Copy link

flackend commented Feb 28, 2024

Latest WSL2 has systemctl support and can automatically map sshd's connection to the Windows host. No need to redirect port.

  1. Make sure Windows OpenSSH works.
  2. In windows, run wsl --update to make sure use latest WSL.
  3. In WSL, run sudo apt-get install openssh-server to install ssh and sudo systemctl enable --now ssh to automatically start ssh when WSL starts.
  4. Run ssh -J windows_user@windows_ip wsl_user@localhost to login to ssh
  5. If step 4 works, add the following content to .ssh/config
Host wsl
  HostName localhost
  User wsl_user
  ProxyJump windows_user@windows_ip
  StrictHostKeyChecking no
  UserKnownHostsFile=/dev/null
  1. Connect to wsl remote in VSCode πŸŽ‰πŸŽ‰πŸŽ‰

This ☝️ ☝️ ☝️ ☝️ Thank you @ajihyf so much!

So much simpler than the other solutions out there.

@astiwana
Copy link

astiwana commented Mar 6, 2024

Thanks a lot, works perfectly!

@rakete1
Copy link

rakete1 commented Mar 22, 2024

Latest WSL2 has systemctl support and can automatically map sshd's connection to the Windows host. No need to redirect port.

  1. Make sure Windows OpenSSH works.
  2. In windows, run wsl --update to make sure use latest WSL.
  3. In WSL, run sudo apt-get install openssh-server to install ssh and sudo systemctl enable --now ssh to automatically start ssh when WSL starts.
  4. Run ssh -J windows_user@windows_ip wsl_user@localhost to login to ssh
  5. If step 4 works, add the following content to .ssh/config
Host wsl
  HostName localhost
  User wsl_user
  ProxyJump windows_user@windows_ip
  StrictHostKeyChecking no
  UserKnownHostsFile=/dev/null
  1. Connect to wsl remote in VSCode πŸŽ‰πŸŽ‰πŸŽ‰

This ☝️ ☝️ ☝️ ☝️ Thank you @ajihyf so much!

So much simpler than the other solutions out there.

Can confirm. This is working like a charm for me as well.

@sqsvp
Copy link

sqsvp commented Mar 22, 2024

How I proceed with connection to WSL2 on remote host.

  1. I've set up OpenSSH server on Windows remote host.
  2. From vscode on local machine i connected to remote Windows host.
  3. While connecting to remote host using SSH select Windows operating system.
  4. After succesful connection to remote Windows host press Ctrl-Shift-P on keyboard, write WSL in opened bar and select WSL: Connect to WSL using Distro in New Window...
  5. Distros of remote Windows host will be listed in dropdown menu.
  6. Select your distro in dropdown menu
  7. Connection to remote WSL distro will start in new window.

Result of connection to remote WSL through ssh

I think it's worth mentioning that I do not have Debian WSL distro on my local machine. This is WSL distro of remote Windows host.

@LRKasri
Copy link

LRKasri commented Apr 4, 2024

Latest WSL2 has systemctl support and can automatically map sshd's connection to the Windows host. No need to redirect port.

1. Make sure Windows OpenSSH works.

2. In windows, run `wsl --update` to make sure use latest WSL.

3. In WSL, run `sudo apt-get install openssh-server` to install ssh and  `sudo systemctl enable --now ssh` to automatically start ssh when WSL starts.

4. Run `ssh -J windows_user@windows_ip wsl_user@localhost` to login to ssh

5. If step 4 works, add the following content to `.ssh/config`
Host wsl
  HostName localhost
  User wsl_user
  ProxyJump windows_user@windows_ip
  StrictHostKeyChecking no
  UserKnownHostsFile=/dev/null
6. Connect to `wsl` remote in VSCode πŸŽ‰πŸŽ‰πŸŽ‰

This works so well for me, thanks a lot!!

@jhanschoo
Copy link

You don't necessarily need these things anymore. It's possible to use Remote-Tunnels together with the WSL extension on the remote.

@vbrozik
Copy link

vbrozik commented May 14, 2024

@jhanschoo I guess you are referring to VS Code. The solutions here show the generic approach which do not require you to use VS Code.

@jhanschoo
Copy link

Thanks, I nevertheless think it's important to note easy solutions when they exist that involve VSCode considering that the topic of the Gist is wrt VSCode. I'm personally aware of the more generic situations but don't use them due to the effort.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment