wsl2固定IP解决方案

有关wsl的介绍、安装、设置详见:Winux之路-WSL 2的使用及填坑

虚拟机访问避免不了某些服务需要固定IP来访问,但是wsl2每次启动后IP有可能会变,所以先临时采取以下方案。第一步只需要操作一次,之后只需要执行第二步中的bat文件

1、首先登陆虚拟机(Ubuntu-20.04示例)创建/etc/wsl.conf,写入以下内容,默认为true,true 将 WSL 设置为生成 /etc/resolv.conf

[network]
generateResolvConf=false

此时的resolv.conf是/run/resolvconf/resolv.conf(generateResolvConf=true的时候自动生成)符号链接文件,需要先删除;DNS列表自行设置

rm /etc/resolv.conf
echo "nameserver 114.114.114.114" > /etc/resolv.conf

2、将以下文本保存为bat文件,管理员运行,目的是这是对应Linux实例的IP地址以及windows wsl网卡的地址。(可以将此文件创建快捷方式到桌面,右键属性-高级中设置为管理员打开,每次只需要双击快捷方式打开一次就行)

wsl相关指令自行研究 对应IP修改为自己合适的

@echo off

wsl -d Ubuntu-20.04 --shutdown

REM 把这里理解为一个开机启动脚本就行
REM ssh若是需要的话;包括数据库等等
wsl -d Ubuntu-20.04 -u root service ssh start

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 Ubuntu-20.04 -u root ip addr add 192.168.50.2/24 broadcast 192.168.50.255 dev eth0
wsl -d Ubuntu-20.04 -u root ip route add 0.0.0.0/0 via 192.168.50.1 dev eth0

powershell -c "Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress 192.168.50.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 192.168.50.0/24;"

REM 启动对应Linux系统,我这里是使用windows terminal,可自行替换为自己的,或者删除以其它方式启动
wt -p Ubuntu-20.04

张子庭博客
请先登录后发表评论
  • latest comments
  • 总共0条评论