When
윈도우에서 우분투를 설치하고 외부에서 SSH로 접속할때
Why
기본적으로 WSL은 내부적으로 아이피가 새로 할당되기 때문에
재부팅이 되고 나면 WSL의 아이피가 달라져서 내 PC와 포트포워딩설정이 먹히지 않게된다.
How
해결방법은 아래 스크립트를 생성후 작업스케쥴러에 등록해주면 된다.
스크립트 생성
C:\Tasks\port_foward.ps1 파일을 생성후 아래 내용을 추가
$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]
# Ubuntu에서 사용하고 있는 서비스 할 포트번호 입력
$ports=@(80, 1000, 2000, 2222, 3000, 5000, 14333, 24333);
#[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 ",";
# 방화벽 제거 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";
}
작업스케쥴러에 등록
- 시작 > 실행 > 작업스케줄러
- 동작 > 작업만들기
- 일반탭
이름: 유닉스포트포워딩
사용자 로그온 여부에 관계없이 실행
가장 높은수준의 권한으로 실행 - 트리거탭
새로만들기 > 시스템 시작시 - 동작탭
-
프로그램 > 스크립트 : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
-
시작 위치 : 위의 스크립트가 존재하는 폴더 Path (예: C:\Tasks)
-
인수 추가 : -ExecutionPolicy Bypass -File .\port_foward.ps1