修改 .wslconfig
先打开 Powershell
停止 wsl
wsl --shutdown
打开 .wslconfig
, 这里使用记事本
notepad.exe C:\Users\你的用户名\.wslconfig
在里面加入配置并保存
[wsl2]
memory=8GB
processors=8
[experimental]
autoMemoryReclaim=gradual
networkingMode=mirrored
dnsTunneling=true
firewall=true
autoProxy=true
添加代理脚本
启动 wsl
后, 直接在 ~
目录下创建 proxy.sh
脚本, 自行修改端口
#!/bin/sh
# hostip=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
hostip=127.0.0.1
wslip=$(hostname -I | awk '{print $1}')
socks_port=socks端口
http_port=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 "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
命令并保存
alias proxy="source ~/proxy.sh"
使用
先 source
一下 ~/.bashrc
或 打开新的 wsl
窗口
proxy set # 开启代理
proxy unset # 关闭代理
proxy test # 测试代理
效果
gelomen in ~ proxy test # 刚打开 `wsl`, 测试: 失败
Host IP: 127.0.0.1
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: 127.0.0.1
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: 127.0.0.1
WSL IP: 192.168.2.108
Try to connect to Google...
Proxy setup failed!