添加脚本设置 wsl2
使用 Windows
的系统代理
添加代理脚本
启动 wsl
后, 直接在 ~
目录下创建 proxy.sh
脚本, 自行修改端口
这个脚本参考了文章 《WSL2中设置脚本以便捷开启命令行代理加速》 - 作者: wadaxiyang
根据实际情况, 自行修改 socks_port
和 http_port
两个端口地址
proxy.sh1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #!/bin/bash
hostip=$(ipconfig.exe | grep -a -A 7 "Windows IP" | grep -a IPv4 | awk -F ' . . . . . . . . . . . . : ' '{print $2}' | tr -d '\r') wslip=$(hostname -I | awk '{print $1}') socks_port=socks端口(代理工具的socks端口) http_port=http端口(代理工具的http端口)
PROXY_HTTP="http://${hostip}:${http_port}" PROXY_SOCKS5="socks5://${hostip}:${socks_port}"
set_proxy(){ export http_proxy="${PROXY_HTTP}" export HTTP_PROXY="${PROXY_HTTP}"
export https_proxy="${PROXY_HTTP}" export HTTPS_proxy="${PROXY_HTTP}"
export ALL_PROXY="${PROXY_SOCKS5}" export all_proxy=${PROXY_SOCKS5}
git config --global http.https://github.com.proxy ${PROXY_HTTP} git config --global https.https://github.com.proxy ${PROXY_HTTP}
echo "Proxy has been opened." }
unset_proxy(){ unset http_proxy unset HTTP_PROXY unset https_proxy unset HTTPS_PROXY unset ALL_PROXY unset all_proxy git config --global --unset http.https://github.com.proxy git config --global --unset https.https://github.com.proxy
echo "Proxy has been closed." }
test_setting(){ echo "Host IP:" ${hostip} echo "WSL IP:" ${wslip} echo "PROXY HTTP:" ${PROXY_HTTP} echo "PROXY SOCKS5:" ${PROXY_SOCKS5} echo "Try to connect to Google..." resp=$(curl -I -s --connect-timeout 5 -m 5 -w "%{http_code}" -o /dev/null www.google.com) if [ ${resp} = 200 ]; then echo "Proxy setup succeeded!" else echo "Proxy setup failed!" fi }
if [ "$1" = "set" ] then set_proxy
elif [ "$1" = "unset" ] then unset_proxy
elif [ "$1" = "test" ] then test_setting else echo "Unsupported arguments." fi
|
修改 .bashrc
在 wsl
里打开 ~/.bashrc
, 在里面添加 alias
命令并保存
.bashrc1
| alias proxy="source ~/proxy.sh"
|
使用
先 source
一下 ~/.bashrc
或 打开新的 wsl
窗口
1 2 3
| proxy set proxy unset proxy test
|
效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| gelomen in ~ proxy test Host IP: 192.168.2.120 WSL IP: 192.168.2.108 Try to connect to Google... Proxy setup failed! gelomen in ~ gelomen in ~ proxy set Proxy has been opened. gelomen in ~ gelomen in ~ proxy test Host IP: 192.168.2.120 WSL IP: 192.168.2.108 Try to connect to Google... Proxy setup succeeded! gelomen in ~ gelomen in ~ proxy unset Proxy has been closed. gelomen in ~ gelomen in ~ proxy test Host IP: 192.168.2.120 WSL IP: 192.168.2.108 Try to connect to Google... Proxy setup failed!
|