Skip to content

Instantly share code, notes, and snippets.

@hdavid0510
Forked from hoonoh/wsl2-portforward.ps1
Last active September 17, 2023 06:06
Show Gist options
  • Save hdavid0510/1b2b5ad70ad6c9fcd3187c7eef43c3af to your computer and use it in GitHub Desktop.
Save hdavid0510/1b2b5ad70ad6c9fcd3187c7eef43c3af to your computer and use it in GitHub Desktop.
wsl2 port forwarding script
#DEBUG/ To check script running time
$start = Get-date
Write-Host "Obtaining WSL2 IP address" -foreground cyan;
$remoteAddr = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteAddr -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteAddr = $matches[0];
Write-Output "WSL2 IP: $remoteAddr";
} else{
Write-Output "WSL2 IP not found, exiting";
exit;
}
#All the ports you want to forward separated by coma
$ports = @(80, 443, 3000, 3001, 3306, 5432, 5500, 6379, '8000-8010', '8080-8100', 8443, 8981, 9229);
$ports_a = $ports -join ",";
Write-Output "Ports to forward: $ports_a";
## You can change the addr to your ip config to listen to a specific address
# $addr='0.0.0.0';
Write-Host "`nRemoving firewall exception rules" -foreground cyan;
$null = Invoke-Expression "Remove-NetFireWallRule -DisplayName 'WSL2 Forwarding' ";
Write-Host "`nAdding firewall exception rules for inbound and outbound" -foreground cyan
$null = Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL2 Forwarding' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
$null = Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL2 Forwarding' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
## Remove all previous v4tov4 rules
Write-Host "`nRemoving all previous v4tov4 forwardings" -foreground cyan
# $regex = [regex] '(\d{2,5}$)'
$prevRoutePorts = Invoke-Expression "netsh interface portproxy show v4tov4" | Select-String '(\d{2,5}$)' -AllMatches | Foreach {$_.Matches} | Foreach{$_.Value};
$prevRoutePortsCount = 0;
Foreach($port in $prevRoutePorts) {
Write-Progress -Activity "Removing existing v4tov4 forwarding" -Status "port $port" -PercentComplete (100 * $prevRoutePortsCount / $prevRoutePorts.length);
# $null = Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port" listenaddress=$addr";
$null = Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port";
$prevRoutePortsCount++;
}
Write-Progress -Activity "Removing existing v4tov4 forwarding" -Completed;
## Add port forward rules
Write-Host "`nAdding v4tov4 forwardings" -foreground cyan
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
if ($port.GetType() -Eq [int]) {
Write-Output "Adding v4tov4 forwarding: $port";
$null = Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$remoteAddr";
} elseif ($port.GetType() -Eq [string]) {
$dashIndex = $port.IndexOf('-');
if ($dashIndex -ge 0) {
Write-Output "Adding v4tov4 forwarding: (range) $port";
$portRange = $port.Split("-");
$portFrom = [int]$portRange[0];
$portTo = [int]$portRange[$portRange.length-1];
$portsCount = $portTo - $portFrom + 1;
$portsDone = 0;
for( $port = $portFrom; $port -le $portTo; $port++ ){
Write-Progress -Activity "Adding v4tov4 forwarding (range $portFrom -> $portTo)" -Status "port $port" -PercentComplete (100 * $portsDone / $portsCount);
$null = Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$remoteAddr";
$portsDone++;
}
Write-Progress -Activity "Adding v4tov4 forwarding (range $portFrom -> $portTo)" -Completed;
}
}
}
#run wsl init script
# Write-Output "`n# running wsl init bash script:`n";
# bash.exe -c "sudo /opt/wsl-init.sh"
# #!/bin/sh -e
# sysctl -w net.ipv4.conf.all.route_localnet=1
# iptables -t nat -I PREROUTING -p tcp -j DNAT --to-destination 127.0.0.1
# sysctl -w fs.inotify.max_user_watches=524288
#DEBUG/ To check script running time
$end = Get-date
'{0,-30} : {1,10:#,##0.00} ms' -f 'Time elapsed: ', ($end - $start).TotalMilliseconds
Write-Host "`n`n`nDONE!" -ForegroundColor Green;
Start-Sleep -Seconds 5
@hdavid0510
Copy link
Author

Breaking changes from original script:

  1. Firewall rule name changed to WSL2 Forwarding from WSL 2 Firewall Unlock.
    To remove previous rule, use in powershell(admin):
Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock'
  1. Not using listen address for netsh portproxy
    Adjust $addr to your ip config to listen to a specific address, and uncomment code accordingly.

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