Skip to content

Instantly share code, notes, and snippets.

@estsaon
Last active April 29, 2024 08:21
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save estsaon/b27452c3ba105c369a5d7c9b1f10c6e7 to your computer and use it in GitHub Desktop.
Save estsaon/b27452c3ba105c369a5d7c9b1f10c6e7 to your computer and use it in GitHub Desktop.
How to SSH into WSL2 on an external Window

WSL:

  1. Install openssh-server:
sudo apt install openssh-server
  1. Add or uncomment following lines in /etc/ssh/sshd_config:
Port 2222
ListenAddress 0.0.0.0
PubkeyAuthentication no
PasswordAuthentication yes
  1. Start the SSH service:
sudo service ssh start

Host Windows:

  1. Add firewall rule for port 2222:
netsh advfirewall firewall add rule name='open port 2222 for wsl2 port fowarding' dir=in action=allow protocol=TCP localport=2222
  1. Run the following powershell script:
param ($ExistingPort=2222, $NewPort=2222)

if ((wsl.exe -d Ubuntu -e sh -c "ifconfig eth0 | grep 'inet '") -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') {
    $WslIp=$matches[0]

    Write-Output "Delete old portproxy:"
    Write-Output "`tlistenaddress=0.0.0.0"
    Write-Output "`tlistenport=$ExistingPort"
    iex "netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=$ExistingPort"

    Write-Output ""
    Write-Output "Add new portproxy:"
    Write-Output "`tlistenaddress=0.0.0.0"
    Write-Output "`tlistenport=$NewPort"
    Write-Output "`tconnectaddress=$WslIp"
    Write-Output "`tconnectport=$NewPort"
    iex "netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=$NewPort connectaddress=$WslIp connectport=$NewPort"
}

The script can be added to the task scheduler to configure the port forwarding automatically.

Guest Windows:

ssh [wsl_username]@[host_windows_ip] -p 2222

https://www.illuminiastudios.com/dev-diaries/ssh-on-windows-subsystem-for-linux/

https://www.hanselman.com/blog/how-to-ssh-into-wsl2-on-windows-10-from-an-external-machine

@lithammer
Copy link

Need to add this to /etc/wsl.conf as well:

[boot]
systemd = true

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