WSL 포트 포워딩 빠르게 가기

포트포워딩 방법 (스크립트)

Windows 환경에서 Powershell로 열어줘야한다.

해당 코드를 복사해서 {filename}.ps1로 저장하고 관리자 권한으로 실행하거나

Powershell을 관리자 권한으로 열고 코드를 복붙하면 된다.

$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';

if( $found ){
  $remoteport = $matches[0];
} else{
  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=@(22,80,1000,2000,3000,4000,5000,8000);


#[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";
}

$ports 에는 열기 원하는 포트를 넣어주면 된다.

 

포트포워딩 방법(수동)

netsh interface portproxy add v4tov4 listenport={로컬포트} connectport={연결할WSL포트} connectaddress={WSL에서 ifconfig 입력시 나오는 IP}

 

 

 

포트포워딩 제대로 되었는지 확인

netsh interface portproxy show v4tov4

 

만약 이상할 경우 초기화 후 재시도

netsh interface portproxy reset

 

PSSecurityException 오류가 발생할 경우

Powershell에서 수동으로 RemoteSigned로 바꿔주자

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

 

 

Remote Signed로 바뀐거 확인됐으면 이 단계 건너뛰기

Get-ExecutionPolicy

------
RemoteSigned  // (Good.)
Restricted    // (No.)

 

WSL에서 ifconfig 가 되지 않을 경우

sudo apt install net-tools