Accessing your WSL2 instance remotely via SSH can be incredibly useful.
Here’s a quick guide to set it up:


1. Install OpenSSH Server

Run the following commands in your WSL2 instance (valid for Debian-like distros):

sudo apt update
sudo apt install openssh-server
sudo nano /etc/ssh/sshd_config

Edit your sshd_config file as needed (e.g., ensure PermitRootLogin is set to no, etc...)


2. Allow SSH Through Windows Firewall


Run the following command:

netsh advfirewall firewall add rule name="WSL SSH Access" dir=in action=allow protocol=TCP localport=22

Or via the GUI, open Windows Defender Firewall settings.
Navigate to Advanced Settings > Inbound Rules.
Add a new rule:

    • Type: Port
    • Port: 22 (or your custom SSH port)
    • Action: Allow the connection
    • Profile: All
    • Name: WSL SSH Access

3. Forward Ports From Windows to WSL

Run the following PowerShell commands:

$wslIP = wsl hostname -I | ForEach-Object { $_.Trim() }
netsh interface portproxy add v4tov4 listenaddress=* listenport=22 connectaddress=$wslIP connectport=22

This ensures SSH connections to your Windows IP are forwarded to WSL.


4. Start the SSH Service

Given that standard methods like enabling it via systemctl do not work, we have to start the SSH server manually.

From the Linux WSL:

sudo /usr/sbin/service ssh start

Now, you can SSH into your WSL2 instance using your Windows IP address!

ssh user@<windows_ip>

Make the Solution Persistent Across Restarts

But the access will not work after a restart of the windows machine given that the WSL IP address would change.
To make SSH access persist after a system reboot, create a PowerShell script and configure it to run at boot:

💡
The script will both:
- Create the updated forwarding rule with the current WSL IP address
- Start the SSH service

  1. Open Task Scheduler and create a new task:
    • General Tab:
      • Name: WSL SSH Setup
      • Check Run with highest privileges.
      • Select Run whether user is logged on or not.
    • Triggers Tab:
      • Add a trigger with Begin the task set to At startup.
    • Actions Tab:
      • Add an action with:
        • Program/script: powershell.exe
        • Arguments: -ExecutionPolicy Bypass -File "C:\Scripts\wsl-ssh.ps1"
    • Save the task and provide your Windows credentials if prompted.

Save the following script as C:\Scripts\wsl-ssh-setup.ps1:

$wslIP = wsl hostname -I | ForEach-Object { $_.Trim() }
netsh interface portproxy delete v4tov4 listenaddress=* listenport=22
netsh interface portproxy add v4tov4 listenaddress=* listenport=22 connectaddress=$wslIP connectport=22
wsl -d Debian -- sudo /usr/sbin/service ssh start