方案的大致内容就是:既然固定不了wsl2的ip地址,那么就在启动wsl2后主动给它设置一个ip地址。
@echo off
setlocal enabledelayedexpansion
wsl -u root service docker start | findstr "Starting Docker" > nul
if !errorlevel! equ 0 (
echo docker start success
:: set wsl2 ip
wsl -u root ip addr | findstr "192.168.169.2" > nul
if !errorlevel! equ 0 (
echo wsl ip has set
) else (
wsl -u root ip addr add 192.168.169.2/28 broadcast 192.168.169.15 dev eth0 label eth0:1
echo set wsl ip success: 192.168.169.2
)
:: set windows ip
ipconfig | findstr "192.168.169.1" > nul
if !errorlevel! equ 0 (
echo windows ip has set
) else (
netsh interface ip add address "vEthernet (WSL)" 192.168.169.1 255.255.255.240
echo set windows ip success: 192.168.169.1
)
)
pause
另一个版本:
@echo off
rem 以管理员身份运行
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
rem 需要设置的子系统名称
set linux=CentOS7
rem 设置网段
set localnet=192.168.86
rem 设置子系统的ip
set ip=%localnet%.2
wsl -d %linux% -u root ip addr del $(ip addr show eth0 ^| grep 'inet\b' ^| awk '{print $2}' ^| head -n 1) dev eth0
wsl -d %linux% -u root ip addr add %ip%/24 broadcast %localnet%.255 dev eth0
wsl -d %linux% -u root ip route add 0.0.0.0/0 via %localnet%.1 dev eth0
wsl -d CentOS7 -u root echo "nameserver %localnet%.1" ^> /etc/resolv.conf
powershell -c "Get-NetAdapter -IncludeHidden -Name 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress %localnet%.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix %localnet%.0/24"
exit
带着使命来到世上的你,给他人提供价值,才有价值