본문 바로가기
컴퓨터 활용(한글, 오피스 등)/50_1. 운영체제_윈도우

WSL2 프로세스 외부 접속을 위한 포트포워딩

by 3604 2023. 7. 19.
728x90
 

MS의 업데이트로 WSL2 내부에서 실행한 프로세스를 Host windows에서 localhost로 접속이 가능하게끔 되었다.

하지만 해당 프로세스를 아예 외부에서 접속하고자 할 때에는 Host의 ip로 접속이 불가능하다.

이를 위해 포트 포워딩 작업을 해 줘야 하는데, 이를 수행해주는 스크립트를 구글링 속 해외 한 귀인으로부터 얻을 수 있었다. (https://dev.to/vishnumohanrk/wsl-port-forwarding-2e22)

 

1. 아래 스크립트를 작성해서 OOO.ps1 이름으로 저장한다.

ex) C:\ports_wsl.ps1

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {   
  $arguments = "& '" + $myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

$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 {
  Write-Output "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}

$ports = @(3000, 3001, 5000, 5500, 19000, 19002, 19006);

Invoke-Expression "netsh interface portproxy reset";

for ( $i = 0; $i -lt $ports.length; $i++ ) {
  $port = $ports[$i];
  Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$remoteport";
}

Invoke-Expression "netsh interface portproxy show v4tov4";

2. $ports = @(3000, 3001, 5000, 5500, 19000, 19002, 19006); 부분을 수정해 포워딩을 원하는 포트를 추가 혹은 제거한다.

 

3. Windows PowerShell을 관리자 권한으로 실행한다.

 

4. 해당 스크립트를 실행한다.

 

 

※ 이 시스템에서 스크립트를 실행할 수 없으므로 C:\ports_wsl.ps1 파일을 로드할 수 없습니다. 자세한 내용은 about_Executio n_Policies(https://go.microsoft.com/fwlink/?LinkID=135170)를 참조하십시오.  와 같은 오류 발생시 다음 게시글 참고 : (www.leafcats.com/317)

728x90