Skip to content

Instantly share code, notes, and snippets.

@estsaon
Last active July 19, 2024 03:06
Show Gist options
  • 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

@SYXiao2002
Copy link

Before adding the script to the task scheduler, we may change the PowerShell’s execution policy. By default, it may prevent scripts from running.

One can view and change the execution policy using the following commands:

View the current execution policy:

Get-ExecutionPolicy

Change the execution policy:

  • Allow script execution (temporary change):
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
  • Permanently allow script execution:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

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