柚子/在WSL2中使用宿主机的代理

Created Sat, 26 Nov 2022 00:00:00 +0000 Modified Thu, 16 Feb 2023 16:07:17 +0000
By Yoyo 254 Words 1 min Page views time Edit

1、创建脚本

下面的命令都需要Root权限 (这个应该不用说吧) vim /usr/bin/proxy

将下面的脚本填入创建的文件中 (第四行Port需要改为自己对应的代理端口号)

#!/bin/sh
hostip=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
port=7890

PROXY_HTTP="http://${hostip}:${port}"
PROXY_SOCKS5="socks5://${hostip}:${port}"
set_proxy(){
        export http_proxy="${PROXY_HTTP}"
        export HTTP_PROXY="${PROXY_HTTP}"

        export https_proxy="${PROXY_HTTP}"
        export HTTPS_proxy="${PROXY_HTTP}"

        git config --global http.proxy "${PROXY_SOCKS5}"
        git config --global https.proxy "${PROXY_SOCKS5}"
        echo "proxy success!"
}

unset_proxy(){
        unset http_proxy
        unset HTTP_PROXY
        unset https_proxy
        unset HTTPS_PROXY
        git config --global --unset http.proxy
        git config --global --unset https.proxy
}

test_setting(){
        echo "Host ip:" ${hostip}
        echo "Current proxy:" $https_proxy
        echo "Git proxy:" $(git config -l)
}

if [ "$1" = "set" ]
then
        set_proxy

elif [ "$1" = "unset" ]
then
        unset_proxy

elif [ "$1" = "test" ]
then
        test_setting
else
        echo "Unsupported arguments."
fi

2、授予脚本可执行权限

sudo chmod +x /usr/bin/proxy

3、运行命令

到这里就完成啦! 以后如需设置代理, 就可以直接使用proxy set来自动设置代理, 使用proxy unset来取消设置代理啦!