使用 SSH 連線 WSL2
阿新 • • 發佈:2020-08-12
問題
將 WSL 升級到 WSL2 之後,用 SSH 連線時出現問題。比如,windows ip為10.10.64.98
,在wsl2 ubuntu 執行 ifconfig
顯示的 ip 地址為 172.18.138.97
,並且每次開關 WSL2 ip 都會變化。
在區域網下的其他機器無法通過 SSH 連線到 WSL2 的機器。
解決方法
- 設定 PowerShell 允許執行指令碼
管理員身份執行 PowerShell 執行以下命令,然後選 Y。
set-ExecutionPolicy RemoteSigned
- 將以下命令儲存為 PowerShell 可執行檔案(字尾名為 ps1)。
需要注意的是 Linux 中的 /etc/ssh/sshd_config
配置檔案的埠需要在 80,443,10000,3000,5000
中,當然也可以修改下面命令中的埠。
$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] #All the ports you want to forward separated by coma $ports=@(80,443,10000,3000,5000); #[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 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"; }
- 每次連線前執行上面儲存的檔案(如果不行可能需要重啟 ssh 服務),然後就可以用 Windows 的 ip 地址和 LInux 中設定的埠連線 WSL2 了。