Skip to content

Instantly share code, notes, and snippets.

@awaismirza
Last active July 31, 2023 23:03
Show Gist options
  • Save awaismirza/12b8f77b65b6dce3e2b2309b2c720fbe to your computer and use it in GitHub Desktop.
Save awaismirza/12b8f77b65b6dce3e2b2309b2c720fbe to your computer and use it in GitHub Desktop.
Setup SSH in WSL2
Follow the guide to setup ssh to WSL2.
Make sure to re run the script when system restarts
# Start SSH Service.
wsl sudo service ssh start
# WSL2 network port forwarding script v1
# for enable script, 'Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser' in Powershell,
# for delete exist rules and ports use 'delete' as parameter, for show ports use 'list' as parameter.
# written by Daehyuk Ahn, Aug-1-2020
# Display all portproxy information
If ($Args[0] -eq "list") {
netsh interface portproxy show v4tov4;
exit;
}
# If elevation needed, start new process
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
# Relaunch as an elevated process:
Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path),"$Args runas" -Verb RunAs
exit
}
# You should modify '$Ports' for your applications
$Ports = (2222,80,443,8080)
# Check WSL ip address
wsl hostname -I | Set-Variable -Name "WSL"
$found = $WSL -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if (-not $found) {
echo "WSL2 cannot be found. Terminate script.";
exit;
}
# Remove and Create NetFireWallRule
Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock';
if ($Args[0] -ne "delete") {
New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $Ports -Action Allow -Protocol TCP;
New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $Ports -Action Allow -Protocol TCP;
}
# Add each port into portproxy
$Addr = "0.0.0.0"
Foreach ($Port in $Ports) {
iex "netsh interface portproxy delete v4tov4 listenaddress=$Addr listenport=$Port | Out-Null";
if ($Args[0] -ne "delete") {
iex "netsh interface portproxy add v4tov4 listenaddress=$Addr listenport=$Port connectaddress=$WSL connectport=$Port | Out-Null";
}
}
# Display all portproxy information
netsh interface portproxy show v4tov4;
# Give user to chance to see above list when relaunched start
If ($Args[0] -eq "runas" -Or $Args[1] -eq "runas") {
Write-Host -NoNewLine 'Press any key to close! ';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}
SSH into a WSL2 host remotely and reliably
Motivation 🐼
My MacBook is screaming at me while working on my heavy Webpack project. I have a powerful Windows 10 PC in my living room and my project runs just fine with WSL2 + VSCode remote, but how do I SSH into WSL from my MacBook remotely?
Let’s get into it 🔥
Make sure openssh-server is installed on your WSL Linux distro (In my case Ubuntu):
sudo apt install openssh-server
2. We need to set a different port for our SSH process, since Windows already uses the default one which usually is 22. I think 2222 is easy to remember.
# edit /etc/ssh/sshd_config with the following three changes
Port 2222
ListenAddress 0.0.0.0
PasswordAuthentication yes
We also need to edit /etc/sudoers.d/ in order to remove the requirement of a password for starting the ssh service, this will come handy later on in the automation section of the article, so add the following line:
%sudo ALL=NOPASSWD: /usr/sbin/service ssh *
After all this we can start the service:
# start the service
service ssh start
3. Now we can forward all the ports we need from the Windows host to the WSL host with the help of @daehahn’s wonderful script. Save the PowerShell script and execute it on your Windows host. Make sure to add/remove ports from $Ports for your specific needs. I patched the script to run the sshd service if its not already running, plus it will help later in Automation.
4. After you run this script, you should be able to ssh to the WSL host from any remote host on the network! just like this:
ssh wsluser@windows.ip -p 2222
Automation 🏃
Since WSL2 is using a dynamic IP, each time a restart occurs our port forwarding rules will not work anymore, this is a well known issue in the WSL community. In order to overcome this issue we should run our PowerShell script every time Windows boots.
Press Win+R on Windows and enter shell:startup. This will open the Startup folder. Right click and create a new Shortcut.
Target: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command “C:\scripts\wsl-ports.ps1”
Right click our new shortcut and under properties change Start In to the folder which contains our WSL script, in our case:C:\scripts\wsl-ports.ps1
You should try to run the Shortcut to make sure it works.
Done! 🎉
Now each time you boot, our Startup task will execute the script which starts the SSH service and forwards the needed ports so you can easily SSH/VSCode Remote into your WSL Host from every device on the Network.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment