Skip to content

WSL 相关的坑

创建防火墙规则

New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow

通过设置 hosts 防止 wsl2 的 IP 动态变化

Windows11 可以配置 /etc/wsl.conf

[boot]
command = "/usr/local/humi/wsl-boot-script.sh"

获取 wsl2 IP 的脚本

bash
#/bin/bash
HOST_IP=$(dig $(hostname).local A +short|head -n 1)
HOST_NAME=humi.host.wsl
#sed -i "s/^.*\( ${HOST_IP}\)$/$\1/g" /etc/hosts
sed -i "/${HOST_NAME}/d" /etc/hosts
echo '#HUMI HOSTNAME' >> /etc/hosts
echo $HOST_IP $HOST_NAME>> /etc/hosts

或者通过 systemd 来实现

配置/etc/wsl.conf

systemd
[boot]
systemd = true

编辑 /etc/systemd/system/wslhost.service

systemd
[Unit]
Description=My wslhost Service

[Service]
Type=oneshot
ExecStart=/bin/bash -c "/usr/local/humi/wsl-boot-script.sh"

[Install]
WantedBy=multi-user.target

然后启用服务

bash
sudo systemctl enable wslhost.service
sudo systemctl start wslhost.service

提取 ip

bash
ip addr show eth0 |awk '/inet /{print $2}' |cut -d '/' -f1|head -n 1