wsl2 配置静态网络 端口映射
1.原因:wsl2 ubuntu20.04主机开启后 ip是动态获取的
2.需求:是把wsl2虚拟适配器的设置成静态的
3.操作:
3.1.windows设置
powershell以管理员身份执行以下语句:
Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress 172.22.0.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 172.22.0.0/24;
windows开机自启动
windwos + r 调出运行
shellstartup 调出开机自启动目录
写脚本
vim wsl2network.bat
@ECHO OFF
setlocal EnableDelayedExpansion
PUSHD %~DP0 & cd /d "%~dp0"
%1 %2
mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :target","","runas",1)(window.close)&goto :eof
:target
powershell -c "Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress 172.22.0.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 172.22.0.0/24;"
3.2.ubuntu设置网络
3.2.1在环境变量中添加以下脚本
cat ~/.bashrc
if [ "$(ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | head -n 1)" != "172.22.0.2/24" ];
then
sudo ip addr del $(ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | head -n 1) dev eth0
sudo ip addr add 172.22.0.2/24 broadcast 172.22.0.255 dev eth0
sudo ip route add 0.0.0.0/0 via 172.22.0.1 dev eth0
sudo echo nameserver 192.168.50.1 > /etc/resolv.conf
fi
3.2.2.免密sudo权限
为了执行上一步,需要这个权限。
在 /etc/sudoers 里添加:
UserName ALL=(ALL) NOPASSWD:ALL
3.2.3.配置DNS
在 /etc/wsl.conf 文件写入
[network]
generateResolvConf = false # 不自动生成dns配置,必须
generateHosts = false # 是否生成hosts文件,可选
[interop]
enabled = false # 不能调用Windows进程,可选
appendWindowsPath = false # 不添加Windows路径,可选
在 /etc/wsl.resolv文件写入(如果原来是软连接文件,需要先删除)
nameserver 223.5.5.5 # 写入你本地最好用的dns就行
3.3.设置端口映射
netsh interface portproxy add v4tov4 listenport=80 listenaddress=0.0.0.0 connectport=80 connectaddress=172.22.0.2
netsh interface portproxy add v4tov4 listenport=22 listenaddress=0.0.0.0 connectport=22 connectaddress=172.22.0.2
基本操作
wsl -- ifconfig eth0
新增转发规则
netsh interface portproxy add v4tov4 listenport=22 listenaddress=0.0.0.0 connectport=22 connectaddress=172.22.0.2
查看所有转发规则
netsh interface portproxy show all
删除转发规则
netsh interface portproxy delete v4tov4 listenaddress=192.168.88.110 listenport=9988
重置转发规则
netsh interface portproxy reset