WSL 代理配置脚本

 ·  2026-07-25

用于在 WSL(Windows Subsystem for Linux)中自动配置代理,连接到 Windows 主机的代理服务。

使用方法

将以下脚本添加到 ~/.bashrc 文件中,然后执行 source ~/.bashrc 使其生效。

脚本代码

cat >> ~/.bashrc <<'EOF'
function setwinproxy {
# 优先获取无线网卡IP
WIN_IP=$(powershell.exe "
\$wifiIp = (Get-NetIPAddress | Where-Object {
    \$_.InterfaceAlias -match 'WLAN|Wi-Fi' -and
    \$_.AddressFamily -eq 'IPv4' -and
    \$_.IPAddress -notlike '127.*' -and
    \$_.IPAddress -notlike '169.254.*'
}).IPAddress | Select-Object -First 1

if (\$wifiIp) { \$wifiIp } else {
    (Get-NetIPAddress | Where-Object {
        \$_.InterfaceAlias -match 'Ethernet|以太网' -and
        \$_.AddressFamily -eq 'IPv4' -and
        \$_.IPAddress -notlike '127.*' -and
        \$_.IPAddress -notlike '169.254.*'
    }).IPAddress | Select-Object -First 1
}
")
WIN_IP=$(echo "$WIN_IP" | tr -d '\r\n ')

if [ -z "$WIN_IP" ]; then
    echo "❌ 获取Windows本机IP失败!检查网络连接"
    return 1
fi

export HTTP_PROXY=http://${WIN_IP}:7890
export HTTPS_PROXY=http://${WIN_IP}:7890
export ALL_PROXY=socks5://${WIN_IP}:7890
export http_proxy=http://${WIN_IP}:7890
export https_proxy=http://${WIN_IP}:7890
export all_proxy=socks5://${WIN_IP}:7890

echo "✅ WSL代理已启用"
echo "📍 Windows主机IP: ${WIN_IP}:7890"
}

function clearproxy {
unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy
echo "❌ 所有代理环境变量已清空"
}
EOF
source ~/.bashrc

函数说明

函数名功能
setwinproxy自动获取 Windows 主机 IP 并配置代理环境变量
clearproxy清空所有代理环境变量

配置说明

  • 代理端口: 默认使用 7890 端口(适用于 Clash、V2Ray 等代理软件)
  • IP 获取顺序: 优先获取无线网卡 IP,如果失败则获取有线网卡 IP
  • 环境变量: 同时设置了大写和小写的代理环境变量,确保兼容性
 
下一篇:没有了
评论
溯境集. All Rights Reserved.