wsl2 port forwarding script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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]; | |
echo $remoteAddr; | |
} else{ | |
echo "The Script Exited, the ip address of WSL 2 cannot be found"; | |
exit; | |
} | |
#[Ports] | |
#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); | |
#[Static ip] | |
#You can change the addr to your ip config to listen to a specific address | |
$addr='0.0.0.0'; | |
$ports_a = $ports -join ","; | |
$firewallRuleName = "WSL 2 Firewall Unlock"; | |
#Remove Firewall Exception Rules | |
iex "Remove-NetFireWallRule -DisplayName '$firewallRuleName' "; | |
#adding Exception Rules for inbound and outbound Rules | |
iex "New-NetFireWallRule -DisplayName '$firewallRuleName' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP"; | |
iex "New-NetFireWallRule -DisplayName '$firewallRuleName' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP"; | |
#delete all previous v4tov4 rules | |
$regex = [regex] '(\d{2,5}$)' | |
$prevRoutePorts = iex "netsh interface portproxy show v4tov4" | Select-String '(\d{2,5}$)' -AllMatches | Foreach {$_.Matches} | Foreach{$_.Value}; | |
Foreach($port in $prevRoutePorts) { | |
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr"; | |
echo "deleted previously v4tov4 rule on port $port"; | |
} | |
#add port forward rules | |
function addPortForward($listenPort) { | |
iex "netsh interface portproxy add v4tov4 listenport=$listenPort connectport=$listenPort connectaddress=$remoteAddr"; | |
echo "added port $listenPort to v4tov4 portproxy"; | |
} | |
for( $i = 0; $i -lt $ports.length; $i++ ){ | |
$port = $ports[$i]; | |
if ($port.GetType() -Eq [int]) { | |
addPortForward($port); | |
} elseif ($port.GetType() -Eq [string]) { | |
$dashIndex = $port.IndexOf('-'); | |
if ($dashIndex -ge 0) { | |
echo "`n# found range $port"; | |
$portRange = $port.Split("{-}"); | |
$portFrom = [int]$portRange[0]; | |
$portTo = [int]$portRange[$portRange.length-1]; | |
for( $port = $portFrom; $port -le $portTo; $port++ ){ | |
addPortForward($port); | |
} | |
} | |
} | |
} | |
#run wsl init script | |
echo "`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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment