Skip to content

Instantly share code, notes, and snippets.

@rizary
Created August 19, 2020 12:03
Show Gist options
  • Select an option

  • Save rizary/ebcdc02bae7b9b5a2d14ca6f25733f07 to your computer and use it in GitHub Desktop.

Select an option

Save rizary/ebcdc02bae7b9b5a2d14ca6f25733f07 to your computer and use it in GitHub Desktop.
$remoteport = bash.exe -c "ip a | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteport=$remoteport.Split("inet");
foreach ($rp in $remoteport) {
if ($rp -match '172.\d{1,3}\.\d{1,3}\.\d{1,3}') {
$remoteport=$rp;
$remoteport=$remoteport.Split("/");
$remoteport=$remoteport[0].Trim();
break;
}
}
$remoteport;
} else{
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
if ($remoteport -notmatch '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') {
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,87,8081,8080,5432,1111,9000);
#[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 ",";
#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( $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=$remoteport";
}
$host_names='ubuntu.wsl.com';
$file = "$env:SystemRoot\system32\drivers\etc\hosts"
$string2 = $remoteport+' '+$host_names;
$pattern = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} "+$host_names;
$file_c=[System.IO.File]::ReadAllText($file).Trim();
if ($file_c -notmatch $pattern) {
Add-Content -Path $file -Value ('
'+$string2);
}else {
if ($file_c -notmatch $string2) {
$file_c=$file_c -replace $pattern,$string2;
Set-Content $file $file_c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment