Skip to content

Instantly share code, notes, and snippets.

@johzzy
Last active July 23, 2020 02:15
Show Gist options
  • Save johzzy/b12b65856031a497863997e95d37084f to your computer and use it in GitHub Desktop.
Save johzzy/b12b65856031a497863997e95d37084f to your computer and use it in GitHub Desktop.
wsl2 hosts generator
# check wsl running
wslconfig /l /running
if ($LASTEXITCODE -ne 0) {
echo "Please open WSL before RUN 'sudo wsl2.ps1'."
exit;
}
# [Config]
$wsl_hosts = "wsl.local"
$win_hosts = "win.local"
$HOSTS_PATH = "$env:windir\System32\drivers\etc\hosts"
# [Start]
$winip, $wslip = bash -c "ip route | grep default | awk '{print \`$3}';hostname -I | awk '{print \`$1}'"
$found1 = $winip -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$found2 = $wslip -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( !($found1 -and $found2) ){
Write-Output "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
# [Ports]
# All the ports you want to forward separated by coma
$LocalPort="80,443,1935,1985,2222,3000,5000,8000,8080,10000,27701"
# [Static ip]
# You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
# Remove Firewall Exception Rules
Invoke-Expression "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' " | Out-Null
# Adding Exception Rules for inbound and outbound Rules
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $LocalPort -Action Allow -Protocol TCP" | Out-Null
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $LocalPort -Action Allow -Protocol TCP" | Out-Null
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $LocalPort -Action Allow -Protocol UDP" | Out-Null
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $LocalPort -Action Allow -Protocol UDP" | Out-Null
foreach ($port in $LocalPort.Split(',')) {
Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr" | Out-Null
Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$wslip" | Out-Null
}
# C:\msys64\usr\bin\unix2dos.exe $HOSTS_PATH
# echo "unix2dos hosts $LASTEXITCODE"
(Get-Content -Path $HOSTS_PATH | Select-String -Pattern '# managed by w(sl)|(in)_hosts' -NotMatch | Out-String).Trim() + "`n`n$wslip $wsl_hosts # managed by wsl_hosts`n$winip $win_hosts # managed by win_hosts"| Out-File -FilePath $HOSTS_PATH -encoding ascii;
C:\msys64\usr\bin\unix2dos.exe $HOSTS_PATH
Write-Output "unix2dos hosts $LASTEXITCODE"
ipconfig /flushdns | Out-Null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment