• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

WSL의 서버를 host(window)에서 접근 하는 방법

28 Jul 2021

Reading time ~2 minutes

WSL 내에서 웹서버를 띄어서 확인이 안되는 경우 다음과 같이 처리 하여 주세요.

port foward를 위해서는 Netsh를 이용할 예정입니다.

1. net-tools를 WSL 안에 설치 하기

ubuntu 기준으로 다음의 명령어를 이용해서 설치 합니다.

sudo apt install net-tools

powser shell 실행 파일 생성하기

Netsh 설정이된 ps1 의 확장자를 가진 파일을 생성합니다.

다음을 network.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 "IP address could not be found";
  exit;
}

$ports = @(3000, 5500, 8080);

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 advfirewall firewall add rule name=$port dir=in action=allow protocol=TCP localport=$port";
}

Invoke-Expression "netsh interface portproxy show v4tov4";

여기서 중요한 것은 $ports = @(3000, 5500, 8080); 부분입니다.

forward 할 port를 작성합니다.

3. 실행하기

powser shell에서 실행을 하면 다음과 같은 오류 메시지를 받을 수 있습니다.

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

해결을 위해서 powser shell을 관리자 모드로 실행하고, Set-ExecutionPolicy -ExecutionPolicy RemoteSigned 명령어로 실행 규칙을 변경합니다.

$> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

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

이후 다시 실행하면 다음과 같이 정상 동작을 확인 할 수 있습니다.

$> .\network.ps1


확인됨


확인됨


확인됨


ipv4 수신 대기:             ipv4에 연결:

주소            포트        주소            포트
--------------- ----------  --------------- ----------
*               5500        192.168.254.148 5500
*               3000        192.168.254.148 3000
*               8080        192.168.254.148 8080

4. 테스트

WSL에서 5500 포트로 웹을 띄우과 브라우져에서 접속하여 확인하면 잘 동작 하는 것을 확인 할 수 있습니다.

참고 자료

  • WSL Port Forwarding
  • [PowerShell] Error: 이 시스템에서 스크립트를 실행할 수 없으므로 …


wslportforwrding Share Tweet +1