条件是你安装好了WSL2, 也就是说你的Windows版本在Windows 10 Version 2004 以上.
本文的WSL2版本是Ubuntu 20.04
Step0 将WSL2的默认用户改为root, 方法参见这篇文章
Step1 打开Ubuntu, 以官网指令安装宝塔面板, 并记录面板路径和账号, 密码
Step2 设置宝塔面板开机自启, 方法参见这篇文章.
以下操作为映射端口, 可以用127.0.0.1访问wsl2 web服务器
Step3 在Windows下, 新建文本文档, 内容如下
$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
# 在下面这行填入所有会使用的Ubuntu的端口, 以逗号分隔
$ports=@(8888,80);
#[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";
}
把要使用的Ubuntu端口, 填入上面文本文档的相应位置
-> 将该文本文档保存为 C:\_green_config\wsl2port.ps1
Step4 允许Powershell运行脚本:
点Win10任务栏上的搜索按钮, 输入powershell
-> 在Windows Powershell上点右键
-> 点"以管理员身份运行"
-> 运行如下指令
Set-ExecutionPolicy RemoteSigned
Step4.1 测试ps1脚本
还是在刚才这个管理员身份打开的powershell中, 运行
powershell -file C:\_green_config\wsl2port.ps1
然后运行
netsh interface portproxy show all
这时你可以看到windows映射的wsl的端口
检查是否是正确的
Step5 在windows下, 按Win键+R键
->运行"taskschd.msc"
-> 点"操作" ->"创建任务"
Step6 在"常规" 页面, 像下面这个搞

Step7 点"触发器" -> 点"新建" -> 在"新建触发器" 页面, 像下面这么搞

->确定
Step8 点"操作"
-> 点"新建"
-> 在"程序或脚本"中填写
powershell -file C:\_green_config\wsl2port.ps1
-> 确定, 如下图

-> 再次确定后如下图

Step9 点"条件", 像下面这么搞

Step10 点"设置" , 像下面这么搞

Step11 重启电脑
然后你就可以用127.0.0.1:8888加上后台路径访问宝塔面板啦
这样操作后, 可能你每次开机后得等10秒, 才能用宝塔面板
以上, 曾实例化于Win10 ver 2004 + WSL2/Ubuntu 20.04