すごくメモ帳

すごくほぼメモ帳ぐらいなブログ

WSL2 ポートフォワーディング設定 (PowerShell) [How to port forwarding settings of WSL2]

以下のPower Shell スクリプトを実行

22番ポートをポートフォワーディングしている。

# portf.ps1
$wsl_ip = wsl -e hostname -I
$wsl_ip -match "\d*\.\d*\.\d*\.\d*"
$wsl_ip = $matches[0]
$ports = @(22)
$ip = "0.0.0.0"
$ports_a = $ports -join ","
Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock'
New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP
New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP
foreach($port in $ports){
    netsh interface portproxy delete v4tov4 listenport=${port} listenaddress=${ip}
    netsh interface portproxy add v4tov4 listenport=${port} listenaddress=${ip} connectport=${port} connectaddress=${wsl_ip}
}

再起動毎に実行しないといけない。めんどくさい。