Skip to content

Instantly share code, notes, and snippets.

@a2902793
Forked from daehahn/wsl2-network.ps1
Created October 16, 2020 10:48
Show Gist options
  • Save a2902793/12232d45a8c8729b11e2a4defd8f7caa to your computer and use it in GitHub Desktop.
Save a2902793/12232d45a8c8729b11e2a4defd8f7caa to your computer and use it in GitHub Desktop.
WSL 2 TCP NETWORK FORWARDING
# 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.
# written by Daehyuk Ahn, Aug-1-2020
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
}
$Addr = "0.0.0.0"
$Ports = (22,80,443,8080)
$Param = $Args[0].ToLower()
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 'WSL2 Firewall Unlock';
if ($Param -ne "delete") {
New-NetFireWallRule -DisplayName 'WSL2 Firewall Unlock' -Direction Outbound -LocalPort $Ports -Action Allow -Protocol TCP;
New-NetFireWallRule -DisplayName 'WSL2 Firewall Unlock' -Direction Inbound -LocalPort $Ports -Action Allow -Protocol TCP;
}
# Add each port into portproxy
Foreach ($Port in $Ports) {
netsh interface portproxy delete v4tov4 listenaddress=$Addr listenport=$Port > null;
if ($Param -ne "delete") {
netsh interface portproxy add v4tov4 listenaddress=$Addr listenport=$Port connectaddress=$WSL connectport=$Port > 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');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment