问题
将 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 了。