獲取 WSL2 IP 地址
在 WSL2 中,要訪問 Windows 上運行的網絡應用(例如在 Windows 上運行的代理軟件、SQL 服務器等),需要使用 WSL2 的 IP 地址,而不是 localhost
。
WSL2 的 IP 地址保存在 /etc/resolv.conf
文件中的 nameserver
,可以通過一下命令獲取:
cat /etc/resolv.conf|grep nameserver|awk '{print $2}'
設置環境變量
假定代理軟件的默認 sock5 的監聽端口為 10808
export PROXY_PORT=10808
export WINDOWS_NAMESERVER=`cat /etc/resolv.conf|grep nameserver|awk '{print $2}'`
export WIN_PROXY=socks5://$WINDOWS_NAMESERVER:$PROXY_PORT
export HTTP_PROXY=$WIN_PROXY
export HTTPS_PROXY=$WIN_PROXY
Windows 防火牆以及代理軟件設置
默認情況下代理軟件是不能通過防火牆的,需要允許代理軟件通過 Windows 的防火牆,設置如圖:
代理軟件必須開啟允許來自局域網的連接(connection from private net work)
現在可以通過 curl www.google.com
來測試代理是否生效,如果控制台有輸出即為設置成功。
最后附上一個腳本,可以通過 proxy start|stop|status
開啟、關閉或者檢查代理。
#!/bin/bash
PROXY_PORT=10808
WINDOWS_NAMESERVER=`cat /etc/resolv.conf|grep nameserver|awk '{print $2}'`
ALL_PROXY=socks5://$WINDOWS_NAMESERVER:$PROXY_PORT
GIT_HTTP_PROXY=`git config --global --get http.proxy`
GIT_HTTPS_PROXY=`git config --global --get https.proxy`
case $1 in
start)
export HTTP_PROXY=$ALL_PROXY
export HTTPS_PROXY=$ALL_PROXY
if [ "`git config --global --get http.proxy`" != $ALL_PROXY ]; then
git config --global http.proxy $ALL_PROXY
git config --global https.proxy $ALL_PROXY
fi
;;
stop)
unset HTTP_PROXY
unset HTTPS_PROXY
if [ "`git config --global --get http.proxy`" = $ALL_PROXY ]; then
git config --global --unset http.proxy
git config --global --unset https.proxy
fi
;;
status)
echo "HTTP_PROXY:" $HTTP_PROXY
echo "HTTPS_PROXY:" $HTTPS_PROXY
echo "GIT_HTTP_PROXY: `git config --global --get http.proxy`"
echo "GIT_HTTPS_PROXY: `git config --global --get https.proxy`"
;;
*)
echo "usage: source $0 start|stop|status"
;;
esac
使得命令生效的話還需要在 ~/.bashrc
文件末尾新增一條命令(~/.set-wsl2-proxy.sh
表示腳本路徑):
alias proxy="source ~/set-wsl2-proxy.sh"