Skip to content

Instantly share code, notes, and snippets.

@beshkenadze
Forked from estsaon/wsl-port-forwarding.md
Last active April 19, 2023 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beshkenadze/eab4f898bf1ba24191aae838a1d8a60c to your computer and use it in GitHub Desktop.
Save beshkenadze/eab4f898bf1ba24191aae838a1d8a60c 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:
$wsl_ip = wsl.exe -d Ubuntu -e sh -c "ip addr show eth0 | grep 'inet '"
$found = $wsl_ip -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$wsl_ip = $matches[0];
iex "netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=2222"
iex "netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=2222 connectaddress=$wsl_ip connectport=2222"
iex "netsh advfirewall firewall add rule name='open port 2222 for wsl2 port fowarding' dir=in action=allow protocol=TCP localport=2222"

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

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