1. 网桥配置固定ip
这种模式不稳定,wsl经常崩溃
@echo off
setlocal enabledelayedexpansion
::先停掉可能在跑的wsl实例
wsl --shutdown ubuntu
if !errorlevel! equ 0 (
::检查WSL有没有我需要的IP
wsl -u root ip addr | findstr "192.168.3.100" > nul
if !errorlevel! equ 0 (
echo wsl ip has set
) else (
::IP不存在则绑定IP
wsl -u root ip addr add 192.168.3.100/24 broadcast 192.168.3.255 dev eth0 label eth0:1
echo set wsl ip success: 192.168.3.100
)
::检查宿主机有没有我需要的IP
ipconfig | findstr "192.168.3.200" > nul
if !errorlevel! equ 0 (
echo windows ip has set
) else (
::IP不存在则绑定IP
netsh interface ip add address "vEthernet (WSL)" 192.168.3.200 255.255.255.0
echo set windows ip success: 192.168.3.200
)
)
::为主机设置SSH转发端口
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=22 connectaddress=192.168.3.100 connectport=22
pause
wsl无法ping通windows
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow
允许wsl通过防火墙
2.另一种模式,自动配置wsl2 host
WSL2 启动时会自动变换IP,IP地址不可固定。使用Localhost有时候可以连接上去,有时候连接不上去。
现在设置一个固定的host来配置WSL2
1. 配置Linux 获取IP启动脚本
如果无法写入,则需要在windows配置etc目录的权限,更改所属组,让User也有写入权
cd /etc
touch initWsl.sh
chmod 775 initWsl.sh
chmod 777 /mnt/c/Windows/System32/drivers/etc/hosts
vim initWsl.sh
initWsl.bash
#! /bin/sh
# 启动对应服务
#service ssh ${1}
#service docker ${1}
# 设置本地Wsl2域名,默认为wsl2host
ipaddr=$(ip -4 addr show dev eth0 | egrep 'inet ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})' | awk '{print $2}' | awk -F/ '{print $1}')
hostName='wsl.local'
sed -i "/${hostName}/d" /mnt/c/Windows/System32/drivers/etc/hosts
echo "${ipaddr} ${hostName}" >> /mnt/c/Windows/System32/drivers/etc/hosts
sed -i "/${hostName}/d" /etc/hosts
echo "${ipaddr} ${hostName}" >> /etc/hosts
winip=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
winhost='win.local'
sed -i "/${winhost}/d" /etc/hosts
echo "${winip} ${winhost}" >> /etc/hosts
./initWsl.sh start
2. 配置Windows 启动运行脚本
- 进入 C:\Users\hanli\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
- 创建Ubuntu.vbs
Set ws = CreateObject("Wscript.Shell")
ws.run "wsl -d Ubuntu -u root /etc/initWsl.sh start", vbhide
- 执行Ubuntu.vbs
3. 通过localhost访问
curl localhost:port
即可访问到wsl2的端口