Created
June 23, 2020 05:55
-
-
Save WinMin/eb121ae4394a1511c51a3a813f9ea365 to your computer and use it in GitHub Desktop.
wsl2 open port
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
param($port, $op='open', $protocol='tcp') | |
#Remove Firewall Exception Rules | |
Function removeFirewall(){ | |
Invoke-Expression "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock *' "; | |
Invoke-Expression "netsh interface portproxy reset"; | |
} | |
Function openPort($proto, $port, $addr, $wsladdr){ | |
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock $proto $port' -Direction Outbound -LocalPort $port -Action Allow -Protocol $proto"; | |
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock $proto $port' -Direction Inbound -LocalPort $port -Action Allow -Protocol $proto"; | |
Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr protocol=$proto"; | |
Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$wsladdr protocol=$proto"; | |
} | |
Function closePort($proto, $port, $addr){ | |
Invoke-Expression "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock $proto $port' "; | |
Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr protocol=$proto"; | |
} | |
if ($port){ | |
if ($port -eq 'remove'){ | |
$op = 'remove' | |
} | |
}else{ | |
echo "no operation specified" | |
exit | |
} | |
$wsladdr = bash.exe -c "ifconfig eth0 | grep 'inet '" | |
$found = $wsladdr -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; | |
$addr = "0.0.0.0" | |
if( $found ){ | |
$wsladdr = $matches[0]; | |
} else{ | |
echo "The Script Exited, the ip address of WSL 2 cannot be found"; | |
exit; | |
} | |
switch($op){ | |
'remove' { | |
removeFirewall | |
} | |
'open' { | |
openPort $protocol $port $addr $wsladdr | |
} | |
'close' { | |
closePort $protocol $port $addr | |
} | |
Default { | |
echo 'unknown operation' | |
exit | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment