Skip to content

Instantly share code, notes, and snippets.

@robearlam
Last active June 29, 2023 12:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robearlam/4290a98dd2870e4b16dd50fbdc690d7b to your computer and use it in GitHub Desktop.
Save robearlam/4290a98dd2870e4b16dd50fbdc690d7b to your computer and use it in GitHub Desktop.
$remoteport = bash.exe -c "ip addr show eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteport = $matches[0];
} else{
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
Write-Host 'WSL2 IP:' $remoteport
#[Ports]
#All the ports you want to forward separated by coma
$ports=@(80,443,8200);
#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addresses=@('127.0.0.1', '192.168.1.128');
$ports_a = $ports -join ",";
#Remove Firewall Exception Rules
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";
#adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
for( $j = 0; $j -lt $addresses.length; $j++) {
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
$addr = $addresses[$j];
Write-Host "Adding mapping for port $($addr):$($port)"
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment