内容纲要
本文内容强调:背景 → 原理 → 脚本 → 使用 → 常见坑 → 最佳实践,一次写清楚,后面不用再解释。
在使用 WSL(Windows Subsystem for Linux)进行开发时,一个绕不开的问题是:
如何让 WSL 的网络流量走 Windows 宿主机上的 Clash 代理?
很多人经历过以下场景:
- WSL 里
git clone慢到怀疑人生 pip / npm / apt访问外网失败- 明明 Windows 浏览器能上网,WSL 却不行
- 以前配过一次代理,现在完全忘了端口和方式
本文给出一套稳定、可复用、无需记忆的一键方案。
一、核心思路(先讲清原理)
关键事实只有三点:
- WSL 是独立的 Linux 网络命名空间
- Windows 和 WSL 通过虚拟网关通信
- Clash 实际运行在 Windows 上
因此,正确的链路应当是:
WSL → Windows 网关 IP → Clash(7890)→ Internet
也就是说,WSL 并不能直接使用 127.0.0.1:7890,
而必须指向 Windows 在 WSL 里的网关 IP。
这个 IP 是动态的,但可以自动获取。
二、目标效果
我们希望最终做到:
- 一条命令开启代理
- 一条命令关闭代理
- 自动识别 Windows IP
- 不修改系统配置
- 不污染长期环境变量
- 可随时查看状态
三、一键脚本实现
1. 新建脚本文件
nano ~/wsl-clash.sh
2. 脚本完整内容
#!/usr/bin/env bash
# =========================
# WSL → Windows Clash Proxy
# Port: 7890
# =========================
CLASH_PORT=7890
get_windows_ip() {
ip route | awk '/default/ {print $3}'
}
enable_proxy() {
WIN_IP=$(get_windows_ip)
if [ -z "$WIN_IP" ]; then
echo "[ERROR] Failed to detect Windows IP"
return 1
fi
export http_proxy="http://${WIN_IP}:${CLASH_PORT}"
export https_proxy="http://${WIN_IP}:${CLASH_PORT}"
export HTTP_PROXY="$http_proxy"
export HTTPS_PROXY="$https_proxy"
export ALL_PROXY="socks5://${WIN_IP}:${CLASH_PORT}"
echo "[OK] WSL proxy enabled"
echo " Windows IP : $WIN_IP"
echo " HTTP Proxy : $http_proxy"
}
disable_proxy() {
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY
echo "[OK] WSL proxy disabled"
}
proxy_status() {
echo "http_proxy = ${http_proxy:-<not set>}"
echo "https_proxy = ${https_proxy:-<not set>}"
echo "ALL_PROXY = ${ALL_PROXY:-<not set>}"
}
case "$1" in
on)
enable_proxy
;;
off)
disable_proxy
;;
status)
proxy_status
;;
*)
echo "Usage:"
echo " source ~/wsl-clash.sh on"
echo " source ~/wsl-clash.sh off"
echo " source ~/wsl-clash.sh status"
;;
esac
四、正确的使用方式(非常关键)
⚠️ 必须使用 source 执行脚本
source ~/wsl-clash.sh on
关闭代理:
source ~/wsl-clash.sh off
查看状态:
source ~/wsl-clash.sh status
原因很简单:
环境变量只对当前 shell 生效,不能用 bash xxx.sh。
五、验证是否真的生效
curl https://www.google.com -I
如果返回 HTTP 头,说明:
- Windows Clash 正在运行
- 已开启「允许局域网连接」
- 7890 端口可用
六、常见坑与排查思路
1. 连不上网?
按顺序检查:
- Windows Clash 是否启动
- 是否开启 Allow LAN
- Clash 监听端口是否为
7890 - Windows 防火墙是否拦截
2. 为什么不用 127.0.0.1?
因为在 WSL 中:
127.0.0.1是 WSL 自己- Windows 的 localhost 不可直连
- 必须通过虚拟网关 IP
七、提升使用体验(推荐)
加一个别名,使用更自然:
nano ~/.bashrc
加入:
alias clash='source ~/wsl-clash.sh'
生效后:
clash on
clash off
clash status
八、为什么推荐这种方式?
相比“写死配置”的方案,这种方式具备:
- 动态适配 Windows IP
- 不影响系统级行为
- 不干扰 Docker / CI
- 出问题可秒级恢复
本质上,这是把代理当作“能力”,而不是“环境绑定”。
九、可扩展方向
这套方案可以很自然地升级为:
- 自动检测 Clash 是否在线
- Docker / apt / git 单独代理策略
- 多端口、多代理配置切换
- WSL 启动自动注入
如果你后续要做成 工程级开发环境模板,这一步是非常干净的起点。