我的wsl2 安装的ubuntu 20.04 , 脚本如下, 具体看注释.
#!/bin/bash
#把wsl的IP导出为全局变量,方便传参(亦可直接给值).
export hostIP=`ifconfig | grep 'broadcast' | awk '{print $2}'`
#调用windows的powershell 新建线程执行.
powershell.exe Start-Process powershell -Verb RunAs \
-ArgumentList "powershell","C:\Users\yangz\developer\uu.ps1","$hostIP"
wsl里的脚本需要调用一个powershell脚本. 要不然执行起来会有问题.(大家可以自行研究下,有更方便的还请留言) .
# Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# 需要执行上面这句,要不然不能执行ps1脚本. 下面这条是默认值.
# Set-ExecutionPolicy -ExecutionPolicy Restricted
# 在 wsl里 执行 export hostIP=`ifconfig | grep 'inet 172' | awk '{print $2}'
# 在wsl 里运行这句话 powershell.exe Start-Process powershell -Verb RunAs -ArgumentList "powershell","C:\Users\yangz\developer\uu.ps1","$hostIP"
# 希望可以修改hosts ,
# 转发主机IP+端口到wsl ,实现局域网访问
(Get-Content C:\Windows\System32\drivers\etc\hosts) | Where-Object {$_ -notmatch 'ubuntu.wsl'} | Set-Content C:\Windows\System32\drivers\etc\hosts
#注意编码,要不然乱码 nul...nul...
"$args ubuntu.wsl" | Out-File -Encoding utf8 -Append C:\Windows\System32\drivers\etc\hosts
# 再配合 netsh interface portproxy add v4tov4 listenport= 9527 listenaddress=0.0.0.0 connectport=9527 connectaddress= ubuntu.wsl
# 重启后不生效的话. 就删除了在重新加 netsh interface portproxy delete v4tov4 listenport= 9527 listenaddress=0.0.0.0
netsh interface portproxy delete v4tov4 listenport= 9527 listenaddress=0.0.0.0
netsh interface portproxy add v4tov4 listenport= 9527 listenaddress=0.0.0.0 connectport=9527 connectaddress= ubuntu.wsl
本人小白,此文抛砖引玉, 希望江湖大侠 走过路过 不吝赐教. /bq