問題
將 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 了。