WSL2设置内网访问
- 前言
- 简单的能让内网访问wsl2
- 布置测试环境
- 获取虚拟机ip及端口转发
- 使用脚本每次启动时进行端口转发
- 配置脚本
- 配置任务计划
前言
近期因为win10 2004要发布(自装了一台新电脑),所以更新了预览版提前体验了下wsl2,在使用docker跑一个简单的ngnix时发现只有宿主机使用localhost可以用浏览器打开对应的ngnix界面,而内网内其他电脑则没办法使用宿主机内网ip访问ngnix界面,而这一点在wsl1中是支持的。在几番查找资料后发现大多解决方法都无效或者过于简单,最后在github上找到了一个自认为相对完美的解决方案,现对这个方案进行一下记录。这里只记录解决方法具体造成这种情况的原因解释的文章有很多了。
简单的能让内网访问wsl2
布置测试环境
- wsl2内使用docker布置ngnix
- 宿主机访问
- 内网访问
获取虚拟机ip及端口转发
因为每次都会用wsl2虚拟机分配一个ip所以使用windows自带的端口转发命令netsh可以实现在获取了虚拟机ip之后转发至wsl2进而进行访问。
-
获得虚拟机ip
如图所示虚拟机ip为172.19.25.67(每次启动都会变) -
设置端口转发(需要管理员权限运行)
1interface portproxy add v4tov4 listenport=【宿主机windows平台监听端口】 listenaddress=0.0.0.0 connectport=【wsl2平台监听端口】 connectaddress=【wsl2平台ip】
各项参数需根据实际情况进行调整
然后查看下端口转发状态:1netsh interface portproxy show all
如图所示端口转发成功。 -
测试内网访问
内网访问成功 -
删除端口转发
1netsh interface portproxy delete v4tov4 listenport=【宿主机windows平台监听端口】 listenaddress=0.0.0.0
使用脚本每次启动时进行端口转发
因为每一次重新启动 wsl2的ip都会变动,所以每一次重启都去手动执行端口转发是一件反人类的事情,我在github上找到一个powershell的脚本能够每一次获取虚拟机ip,并进行指定端口转发。同时有看到一个用go语言做类似功能的,但是由于还需要其它非系统原生支持相对比较繁琐,所以没有尝试。
配置脚本
脚本代码如下:
更改ports=@ 对应的端口即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | $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=@(9696); #[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"; } |
索引自 github
1.将脚本保存为 xxxx.ps1
2.使用cmd调用powershell运行脚本,首次执行可能会有报错,因为powershell默认不能直接执行脚本,需要更改一个设置,需在powershell下执行
1 | Set-ExecutionPolicy RemoteSigned |
使之可以执行ps1脚本。
3.执行netsh interface portproxy show all 查看端口
配置任务计划
- win+r 键入taskschd.msc 打开任务计划
- 创建任务
- 进行配置(如图所示)
填写名称并隐藏
用户登录时触发,延迟10s执行
执行的操作为 powershell,将脚本完整路径作为参数
其它一些配置根据自己实际情况进行修改,比如是不是使用笔记本一类的。
(完)