一、创建批处理文件设置静态IP
创建一个批处理文件,比如:D:\CentOS\static_ip.bat,内容如下:
@echo off
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
wsl -d Ubuntu-20.04 -u root ip addr del $(ip addr show eth0 ^| grep 'inet\b' ^| awk '{print $2}' ^| head -n 1) dev eth0
wsl -d CentOS -u root ip addr add 192.168.8.2/24 broadcast 192.168.8.255 dev eth0
wsl -d CentOS -u root ip route add 0.0.0.0/0 via 192.168.8.1 dev eth0
powershell -c "Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress 192.168.8.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 192.168.8.0/24;"
exit
这里的固定IP为192.168.8.2,网关为:192.168.8.1,然后在Ubuntu系统中编辑~/.bashrc,添加如下内容:
if [ `hostname -I` != 192.168.8.2 ]; then
cmd.exe /c "E:\Ubuntu\ubuntu_static_ip.bat" 1>nul
fi
这样就可以在启动wsl2的时候自动设置IP地址为192.168.8.2了。
二、设置DNS
但是无法使用DNS上网,原因是/etc/resolv.conf中的nameserver不是192.168.8.1,文件是WSL自动生成的,如果想不自动生成,可以建立一个文件:/etc/wsl.conf,内容为:
[network]
generateResolvConf = false
则不会自动生成/run/resolvconf/resolv.conf。
由于原来的/etc/resolv.conf是一个软链接,需要删除它,重新创建一个文件。
sudo rm /etc/resolv.conf
然后新建一个/etc/resolv.conf,内容如下:
nameserver 192.168.8.1
即设定nameserver为我们指定的的网关。这样就可以正常上网了.