Skip to content

Instantly share code, notes, and snippets.

@janderudder
Created March 20, 2022 12:07
Show Gist options
  • Save janderudder/7611fcc6a3eebd2741507722d2c75bb2 to your computer and use it in GitHub Desktop.
Save janderudder/7611fcc6a3eebd2741507722d2c75bb2 to your computer and use it in GitHub Desktop.
Make WSL 2 ports accessible from outside
#
# Run this script as admin
#
# The first two variables should be edited
# according to your situation.
#
$ports=@(80,21,154) # the ports you want to open.
$addr='0.0.0.0'; # target address. 0.0.0.0 is good for most cases.
$wslIP = bash.exe -c "hostname -I"
$found = $wslIP -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if(! $wslIP -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') {
echo "WSL's IP cannot be found. Aborting";
exit;
}
$portsStr = $ports -join ",";
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $portsStr -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $portsStr -Action Allow -Protocol TCP";
for ($i = 0; $i -lt $ports.length; $i++) {
$port = $ports[$i];
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$wslIP";
}
@janderudder
Copy link
Author

janderudder commented Mar 20, 2022

Thanks to @edwindijas who created the script that this one heavily borrows from.

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