WSL 网络连通性排查手记


常见现象与第一时间自检

  • apt update 长时间卡住或报错 Temporary failure resolving:说明 DNS 未正确转发。
  • curl https://google.com 失败但 ping baidu.com 正常:多半是代理绕过或证书问题。
  • Windows 能访问公司内网,但 WSL 访问 10.x 网段失败:需要桥接虚拟网卡或添加静态路由。

第一步可执行以下命令快速定位:

ip addr show eth0          # 确认 WSL 虚拟网卡地址
cat /etc/resolv.conf # 查看当前 DNS
curl -I https://www.baidu.com
curl -I https://www.google.com --proxy http://127.0.0.1:7890

DNS 与代理双保险

  1. 锁定自定义 DNS
sudo rm /etc/resolv.conf
echo -e 'nameserver 223.5.5.5\\nnameserver 8.8.8.8' | sudo tee /etc/resolv.conf
sudo chattr +i /etc/resolv.conf

防止 WSL 每次启动重写配置。
2. 自动注入代理环境变量

cat <<'EOF' >> ~/.wsl-proxy.sh
export http_proxy=http://127.0.0.1:7890
export https_proxy=$http_proxy
export all_proxy=socks5://127.0.0.1:7891
alias proxy-on='source ~/.wsl-proxy.sh'
alias proxy-off='unset http_proxy https_proxy all_proxy'
EOF
echo '[[ -f ~/.wsl-proxy.sh ]] && source ~/.wsl-proxy.sh' >> ~/.bashrc

如需在公司网络禁用代理,执行 proxy-off 即可。

访问公司内网的路由写法

当 Windows 能连通 10.x/172.x 内网,但 WSL 无法访问时:

# Windows 端查看网卡信息
Get-NetIPAddress -InterfaceAlias "以太网"

# 假设公司内网网关为 10.20.0.1
wsl.exe -d Ubuntu-22.04 sudo ip route add 10.0.0.0/8 via 10.20.0.1 dev eth0
wsl.exe -d Ubuntu-22.04 sudo ip route add 172.16.0.0/12 via 10.20.0.1 dev eth0

可将命令写入 PowerShell 启动脚本或 WSL ~/.wslconfig 指向的 prelaunchCommand

HTTPS 证书与 Git 访问

  • 若公司自签证书导致 git clone 报错,可将证书添加到 WSL:
sudo cp /mnt/c/path/to/corp.crt /usr/local/share/ca-certificates/
sudo update-ca-certificates
  • Git 走代理:
git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890
  • 避免系统代理污染 Docker:在 .bashrc 中针对 Docker 命令临时清理代理,
alias docker='http_proxy= https_proxy= all_proxy= docker'

常用诊断脚本

#!/bin/bash
echo \"WSL Network Quick Check\"
echo \"- Date:\" $(date)
echo \"- IP:\" $(hostname -I)
echo \"- Default route:\" $(ip route | grep default)
echo \"- DNS:\" $(sed 's/#.*//;/^$/d' /etc/resolv.conf)

for host in baidu.com github.com google.com; do
printf '\\nTesting %s\\n' \"$host\"
curl -Is --max-time 5 \"$host\" >/tmp/curl.log && head -n1 /tmp/curl.log || echo \"Failed\"
done

保存为 ~/bin/wsl-netcheck,赋予执行权限,网络异常时一键排查。


通过固定 DNS、灵活切换代理及补齐路由,WSL 的网络问题大多可以自救解决。保持脚本化习惯,就能在新机器或不同网络环境中快速复现配置。


Author: linda1729
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source linda1729 !
评论
  TOC