Windows-WSL端口映射

windows设置脚本

  • 放入:win+r输入shell:startup再按回车键的目录中
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    wslname = "Ubuntu-20.04" '要转发端口的Linux系统名称,可以通过 wsl -l 命令查看
    wslport = "80" 'Linux系统里要转发的端口
    winport = "80" '转发到Windows上的端口

    '以下代码无需修改
    If WScript.Arguments.Length = 0 Then
    '用于以管理员权限运行,不然没有权限配置端口转发
    CreateObject("Shell.Application").ShellExecute "wscript.exe" _
    , """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
    WScript.Quit
    End if
    set fso = CreateObject("Scripting.FileSystemObject")
    set objShell = CreateObject("WScript.Shell")
    writeip = objShell.Run("cmd /c ""wsl -d "+wslname+" -u root hostname -I"">C:\Windows\Temp\wslip.tmp",0,True)
    set f = fso.OpenTextFile("C:\Windows\Temp\wslip.tmp", 1)
    wslip = f.ReadAll()
    f.Close()
    command = "cmd /c ""netsh interface portproxy add v4tov4 listenport="+winport+" listenaddress=0.0.0.0 connectport="+wslport+" connectaddress="+wslip
    forwarding = objShell.Run(command,0,True)
    fso.deleteFile("C:\Windows\Temp\wslip.tmp")

放行windows防火墙