如何从本地网络访问运行在WSL(Windows Subsystem for Linux)上的web服务器

如何从本地网络访问运行在WSL(Windows Subsystem for Linux)上的web服务器,linux,windows,ubuntu,webserver,windows-subsystem-for-linux,Linux,Windows,Ubuntu,Webserver,Windows Subsystem For Linux,在将Ubuntu安装为Linux的WSLWindows子系统后,我运行了: root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... 并尝试从我的windows计算机访问此web服务器http://0.0.0.0:8000 或http://192.168.1.178:8000 但没有成功,web服务器只能由地址提供http://127.0.0.1:8000 或http://localhost:800

在将Ubuntu安装为Linux的WSLWindows子系统后,我运行了:

root@teclast:~# python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...

并尝试从我的windows计算机访问此web服务器http://0.0.0.0:8000 或http://192.168.1.178:8000 但没有成功,web服务器只能由地址提供http://127.0.0.1:8000 或http://localhost:8000 这意味着我无法从网络中的另一台pc连接到此web服务器。有可能从外部访问WSL吗?

请按照@erazerbrecht共享中提到的步骤,通过提供ip地址而不是使用本地主机和端口号来运行HTTP服务器

例如: root@teclast:~python3-mhttp.server-b192.168.1.1788000 在192.168.1.178端口8000上提供HTTP服务http://192.168.1.178 :8000/ ...

否则,您也可以执行此操作,而不是执行以下操作: 1.转到Windows defender防火墙 2.选择入站 3.创建新规则;下一个 4.选择程序作为规则类型;下一个 5.选择所有程序;下一个 6.选择允许连接;下一个 7.检查所有3个域,私有、公共;下一个 8.提供规则名称 9完成
10您的状态很好

我已经测试了Microsoft WindowsKB4532132的更新,并重新安装了WSL,它可以正常工作。问题似乎与旧windows版本或旧WSL版本有关。

在虚拟机中,执行ifconfig

您将在第一节eth0:inet x.x.x.x中看到您的IP


此x.x.x.x是您必须放入浏览器中的IP。

现有答案中没有一个适合我,因为WSL2运行在自己的虚拟机中,并且有自己的网络适配器。非本地主机请求需要某种类型的网桥或端口转发才能正常工作,即来自同一网络上的另一台主机

我在中找到了一个解决问题的脚本:

$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";
}

从提升的/admin Powershell会话运行此脚本对我来说很有帮助。这允许从同一端口的Windows主机IP访问运行在该端口上的WSL2服务。

可能会对您有所帮助。感谢您的帮助,但服务器仍然只能通过本地主机访问。并且无法从另一台PC连接到此服务器。以下是Microsoft提供的说明。Windows防火墙正在阻止WSL公开的连接。它确实有效。确保用本地windows IP替换IP。此外,在访问网页时,请使用IP:PORT进行访问。我可以确认以下所有说明均无效。对于我来说,在端口8000查看我的IP会在浏览器中显示Windows用户配置文件目录的文档树。但是,Linux HTTP服务器确实看到并记录了请求。这个回答中的两个建议对我在WSL2上都不起作用。服务无法绑定到Windows IP地址,因为WSL2有自己的网络适配器。防火墙也是如此。在Windows中运行服务时,端口已经在工作,因此不再允许它们。@mliby您找到解决方案了吗?