略微加速

略速 - 互联网笔记

wsl2设置主机端口映射

2025-12-10 leiting (23阅读)

标签 Windows Linux

确保 WSL 已更新到最新版

wsl --update
wsl --shutdown


创建启动脚本 /root/port.sh

#!/bin/bash
# 获取 WSL2 IP
WSL_IP=$(hostname -I | awk '{print $1}')

PORT=3000
# 通过 PowerShell 在 Windows 中设置端口转发
/mnt/c/Windows/system32/WindowsPowerShell/v1.0/powershell.exe -Command "Start-Process -Verb RunAs -FilePath 'netsh' -ArgumentList 'interface','portproxy','delete','v4tov4','listenport=$PORT','listenaddress=0.0.0.0'"
/mnt/c/Windows/system32/WindowsPowerShell/v1.0/powershell.exe -Command "Start-Process -Verb RunAs -FilePath 'netsh' -ArgumentList 'interface','portproxy','add','v4tov4','listenport=$PORT','listenaddress=0.0.0.0','connectport=$PORT','connectaddress=$WSL_IP'"


将脚本加入启动 /etc/wsl.conf

[boot]
command=/root/port.sh


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3