WSL2-access-windows-services

zhihuzhuanlanzhuanlan.zhihu.com/p/144583887

固定wsl2 ip地址

因为每次重启系统后, wsl都会分配到不同网段的ip, 所以将其固定ip的方法如下

添加如下的.bat文件, 根据需求修改对应内容

wsl_set_ip.batmicrosoft_wsl
1
2
3
4
5
6
7
8
:: rights of administrator
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit

:: Add an IP address in Ubuntu, named eth0:1
wsl -d Ubuntu -u root ip addr add 192.168.11.100/24 broadcast 192.168.11.255 dev eth0 label eth0:1

:: Add an IP address in Win10
netsh interface ip add address "vEthernet (WSL)" 192.168.11.1 255.255.255.0

启动wsl后,手动执行一次该脚本便设置完成固定ip

windows防火墙放行wsl

因为windows认为wsl的虚拟网卡是公用网络,因此需要添加防火墙策略放行wsl

管理员运行PowerShell

1
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound  -InterfaceAlias "vEthernet (WSL)"  -Action Allow