目录

WIN系统用WSL的端口自动映射脚本

WIN系统通过WSL跑linux,如果需要把linux系统下某个端口给局域网的其他设备使用,是无法直接在防火墙放行端口,去访问的,因为WIN系统下的linux使用的是子网IP,并不是WIN系统的IP,因此需要两步走:

  • 在"Windows Defender 防火墙"放行端口
  • 在WIN系统开启端口转发,将本机端口转发到linux中的对应端口

WIN防火墙设置

在"Windows Defender 防火墙"-高级设置-入站规则-新建规则 规则类型选择“端口”,协议选TCP,特定端口填写要放行的端口号,操作选“允许连接”,填写规则的名称即可。

端口映射设置

建议直接用一个PowerShell脚本处理,将以下代码保存成一个ps1文件即可。例如script.ps1

# 1. 定义需要转发的端口列表 (在这里增加或删除端口)
$Ports = @(8066, 8060)
$ListenIp = "0.0.0.0"

# 2. 检查管理员权限
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "ERROR: Please run this script as Administrator!" -ForegroundColor Red
    Pause
    exit
}

# 3. 获取 WSL IP
$WslIp = (wsl -d Debian hostname -I).Trim().Split(" ")[0]

if (!$WslIp) {
    Write-Host "ERROR: Could not get WSL IP. Is Debian running?" -ForegroundColor Red
    Pause
    exit
}

Write-Host "Target WSL IP: ${WslIp}" -ForegroundColor Cyan
Write-Host "-------------------------------------------"

# 4. 循环处理每个端口
foreach ($Port in $Ports) {
    Write-Host "Processing Port ${Port}..." -ForegroundColor Yellow
    
    # 删除旧规则
    netsh interface portproxy delete v4tov4 listenaddress=$ListenIp listenport=$Port 2>$null
    
    # 添加新规则
    netsh interface portproxy add v4tov4 listenaddress=$ListenIp listenport=$Port connectaddress=$WslIp connectport=$Port
    
    # 检查并添加防火墙规则
    $RuleName = "WSL_Docker_${Port}"
    if (!(Get-NetFirewallRule -DisplayName $RuleName -ErrorAction SilentlyContinue)) {
        New-NetFirewallRule -DisplayName $RuleName -Direction Inbound -Protocol TCP -LocalPort $Port -Action Allow
        Write-Host "Firewall rule created for ${Port}." -ForegroundColor Green
    } else {
        Write-Host "Firewall rule already exists for ${Port}." -ForegroundColor Gray
    }
}

Write-Host "-------------------------------------------" -ForegroundColor Green
Write-Host "SUCCESS! All ports have been forwarded." -ForegroundColor Green
Write-Host "You can access them via http://192.168.193.9:[Port]"
Write-Host "-------------------------------------------" -ForegroundColor Green

Pause

使用时,只需要把$Ports = @(8066, 8060)这里,填入需要映射的端口即可,多个端口用英文逗号隔开。

之后按WIN+X键,以管理员模式 打开POWER SHELL ,通过cd命令定位到脚本文件位置,输入:./script.ps1就能自动开启映射了。

因为每次重启wsl后,linux系统的IP都会变化,因此每次重启wsl后,需要重新运行一次本脚本。