Windows 原生运行Linux如何自由访问互联网 WSL2 使用 Clash for Windows做代理


title: Windows 原生运行Linux如何自由访问互联网 WSL2 使用 Clash for Windows做代理

WSL是微软官方支持的特性,是适用于Linux的Windows子系统(英语:Windows Subsystem for Linux,简称WSL

WSL2是WSL的第二个版本。

WSL2安装攻略请参考

程序员福音!Win10下使用oh-my-zsh全攻略,让Win10开发更顺滑… https://v2fy.com/p/2021-02-10-zsh-win-1612954923000/

作为一个开发者,我经常需要使用命令行从Github获取一些依赖包,但WSL2无法直接使用外层Windows的代理工具,本文提供一种 WSL2 使用 Clash for Windows做代理 的解决方案

打开控制面板

打开控制面板

打开系统安全

打开系统安全

允许应用通过防火墙

允许应用通过防火墙

更改设置,Clash相关的都打勾, 确定

Clash相关的都打勾

打开Clash主界面, 查看windows主机的ip

查看windows主机的ip

在WSL2的虚拟机中运行以下命令

export https_proxy="http://192.168.112.1:7890"
export http_proxy="http://192.168.112.1:7890"
export all_proxy="sock5://192.168.112.1:7890"
export ALL_PROXY="sock5://192.168.112.1:7890"

可以愉快使用代理了

可以愉快使用代理了

在配置文件.zshrc 底部添加以下语句, 让开启关闭代理更方便

alias setp='export https_proxy="http://192.168.112.1:7890";export http_proxy="http://192.168.112.1:7890";export all_proxy="socks5://192.168.112.1:7890";export ALL_PROXY="socks5://192.168.112.1:7890";'
alias unsetp='unset https_proxy; unset http_proxy; unset all_proxy; unset ALL_PROXY;'

在终端输入setp即可开启代理, 输入unsetp 即可解除代理

在终端输入setp即可开启代理-输入unsetp 即可解除代理

解决代wsl主机ip改变的问题

感谢评论区xyf007的提醒

在几次开关机后,上文提到的 192.168.112.1 主机IP可能会改变,为了一劳永逸,我们可以动态获取主机ip, 并存储到hostip变量中,使用hostip替换192.168.112.1

也就是将

alias setp='export https_proxy="http://192.168.112.1:7890";export http_proxy="http://192.168.112.1:7890";export all_proxy="socks5://192.168.112.1:7890";export ALL_PROXY="socks5://192.168.112.1:7890";'
alias unsetp='unset https_proxy; unset http_proxy; unset all_proxy; unset ALL_PROXY;'

替换为

hostip=$(cat /etc/resolv.conf |grep -oP '(?<=nameserver\ ).*')
alias setp='export https_proxy="http://${hostip}:7890";export http_proxy="http://${hostip}:7890";export all_proxy="socks5://${hostip}:7890";export ALL_PROXY="socks5://${hostip}:7890";'
alias unsetp='unset https_proxy; unset http_proxy; unset all_proxy; unset ALL_PROXY;'

小结

对于开发者而言, Windows这种打不过Linux就加入的方式是值得鼓励的!

有了WSL2,配合Windows强大的软件生态,Windows有望成为最适合开发者的操作系统。

开发者:Windows和Linux我全都要!

本文永久更新地址(欢迎来读留言,写评论):

https://www.v2fy.com/p/2021-09-24-windows-clash-wsl2-1632440722000