본문 바로가기
DevOps/WSL2

WSL2 포트 포워딩 방법

by yscho03 2022. 5. 30.
728x90
반응형

포트 포워딩 (Port Forwarding)

WSL2에서 포트를 오픈해도 Windows 호스트 또는 외부에서 접근이 불가하여 Port를 포워딩해주어야 한다.

1. PS1 스크립트 작성

forwarding.ps1 적당한 이름으로 스크립트를 작성한다. 오픈할 포트를 $ports에 넣어주면 된다.

예) $ports=@(8000, 8888);

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{
  echo "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}
$ports=@(8888);
iex "netsh interface portproxy reset";
for( $i = 0; $i -lt $ports.length; $i++ ){
  $port = $ports[$i];
  iex "netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$remoteport";
}
iex "netsh interface portproxy show v4tov4";

2. 관리자 권한으로 실행

다음과 같이 권한 오류가 발생하는 것을 볼 수 있다. Script 권한을 확인 후에 부여하도록 한다.

PS D:\> .\forwarding.ps1
.\forwarding.ps1 : 이 시스템에서 스크립트를 실행할 수 없으므로 D:\forwarding.ps1 파일을 로드할 수 없습니다. 자세한 내용
은 about_Execution_Policies(https://go.microsoft.com/fwlink/?LinkID=135170)를 참조하십시오.
위치 줄:1 문자:1
+ .\forwarding.ps1
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : 보안 오류: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

3. Sciprt 권한 부여

Sciprt 권한을 확인해보자

PS C:\> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined

다음과 같이 실행하여 권한을 부여한다.

PS D:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

실행 규칙 변경
실행 정책은 신뢰하지 않는 스크립트로부터 사용자를 보호합니다. 실행 정책을 변경하면 about_Execution_Policies 도움말
항목(https://go.microsoft.com/fwlink/?LinkID=135170)에 설명된 보안 위험에 노출될 수 있습니다. 실행 정책을
변경하시겠습니까?
[Y] 예(Y)  [A] 모두 예(A)  [N] 아니요(N)  [L] 모두 아니요(L)  [S] 일시 중단(S)  [?] 도움말 (기본값은 "N"): y
PS D:\> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser    RemoteSigned
 LocalMachine       Undefined

4. 재실행

아래와 같이 포워딩이 된 것을 확인할 수 있다.

PS D:\> .\forwarding.ps1



ipv4 수신 대기:             ipv4에 연결:

주소            포트        주소            포트
--------------- ----------  --------------- ----------
*               8888        172.25.67.211   8888
728x90
반응형

'DevOps > WSL2' 카테고리의 다른 글

WSL2 - SSH 설정 및 접속  (0) 2022.05.30