코딩, 개발에 대한 기록 저장소

[WSL] 외부에서 Windows WSL 접근 설정


> Windows 11, WSL 2 기준으로 작성됨

WSL 은 기기의 고정 IP와는 별개로 가상 IP가 주어지는데 이는 부팅할 때마다 변경이 된다.

따라서, 외부에서 WSL에 접근할 수 있게 하려면 

1. 외부에 알려진 IP 의 포트를 windows가 설치된 기기의 IP의 포트에 포워딩해주고
2. 그것을 다시 WSL의 또 다른 IP의 포트에 포워딩 해줘야 한다.

**결과적으로, 일단 windows 에 고정 IP 설정하고 부팅할 때마다 WSL의 IP로 포워딩 해줘야한다.**

windows의 고정 IP 설정 방법은 생략하기로 하고, 아래의 스크립트를 windows의 작업 스케줄러를 통해 부팅시 실행시켜주면 된다.

아래 스크립트는 기기가 재부팅될 때마다 새로 할당되는 WSL의 가상 IP 에 포워드 해주기 위한 PowerShell 스크립트이다.

- 포트포워딩 스크립트(기기의 고정IP:PORT >> WSL의 가상 IP:PORT)

추가로 포트 설정하려면 $ports=@(80,443,22) 에 입력하면 된다.

```
$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]
#All the ports you want to forward separated by coma
$ports=@(80,443,22);

#[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
Invoke-Expression "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";

#adding Exception Rules for inbound and outbound Rules
Invoke-Expression "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
Invoke-Expression "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];
  Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
  Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}
Invoke-Expression "netsh interface portproxy show v4tov4";
```

### 작업 스케줄러 등록
window키 + r 을 눌러 실행창을 띄우고 taskschd.msc 를 실행

- 작업 만들기 선택
- 일반 탭
  - 이름 입력
  - 가장 높은 수준의 권한으로 실행 체크
- 트리거 탭
  - 새로 만들기
  - 작업 시작: 로그온할 때
  - 작업 지연 시간 체크: 30초 (wsl을 먼저 실행하기 위해)
- 동작 탭
  - 새로 만들기
  - 동작: 프로그램 시작
  - 프로그램/스크립트 : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe (powershell 프로그램 경로)
  - 인수 추가 : noprofile -executionpolicy bypass -file "powerShell 스크립트 파일 경로"
- 조건 탭
  - 대부분 체크 해제 (상황에 맞춰 체크)
- 설정 탭
  - 다음 시간 이상 작업이 실행되면 중지 체크 해제
- 확인을 눌러 저장

직접 실행하려면 아래 명령어를 입력한다.
```
PowerShell.exe -ExecutionPolicy Bypass -File "powerShell 스크립트 파일 경로"
```