Created
September 11, 2025 15:15
-
-
Save bitxel/a61ae87eb0465565964832fd765cf178 to your computer and use it in GitHub Desktop.
tun2socks mac start/stop proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -e | |
| ### === 配置区 === | |
| PROXY_HOST="127.0.0.1" # 本机 SOCKS5 地址 | |
| PROXY_PORT="1080" | |
| DEV="utun123" # TUN 网卡名称 | |
| TUNIP="198.18.0.1" # TUN 的 IP | |
| IFACE="en0" # 物理出口网卡 (ifconfig 查看) | |
| REMOTE_HOSTS=("xxx.com" "yyy.com") # 需要直连的上游主机,可填多个 | |
| ### === 配置区 === | |
| NETS=("1.0.0.0/8" "2.0.0.0/7" "4.0.0.0/6" "8.0.0.0/5" "16.0.0.0/4" \ | |
| "32.0.0.0/3" "64.0.0.0/2" "128.0.0.0/1" "198.18.0.0/15") | |
| function resolve_hosts() { | |
| RESOLVED_IPS=() | |
| for h in "${REMOTE_HOSTS[@]}"; do | |
| if [[ "$h" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then | |
| RESOLVED_IPS+=("$h") | |
| else | |
| ip=$(dig +short "$h" | tail -n1) | |
| [[ -n "$ip" ]] && RESOLVED_IPS+=("$ip") | |
| fi | |
| done | |
| } | |
| function start_proxy() { | |
| resolve_hosts | |
| GW=$(route -n get default 2>/dev/null | awk '/gateway:/{print $2}') | |
| [[ -z "$GW" ]] && { echo "❌ 无法获取默认网关"; exit 1; } | |
| echo "✅ 默认网关: $GW" | |
| echo "✅ 直连上游 IP: ${RESOLVED_IPS[*]:-(无)}" | |
| # 启动 tun2socks | |
| nohup ./tun2socks -device "$DEV" -proxy "socks5://$PROXY_HOST:$PROXY_PORT" -interface "$IFACE" 2>&1 > /dev/null & | |
| echo $! > /tmp/tun2socks.pid | |
| sleep 1 | |
| # 配置 TUN | |
| sudo ifconfig "$DEV" "$TUNIP" "$TUNIP" up | |
| # 为上游加直连 | |
| for ip in "${RESOLVED_IPS[@]}"; do | |
| sudo route -n add -host "$ip" "$GW" 2>/dev/null || true | |
| done | |
| # 配置全局路由 | |
| for net in "${NETS[@]}"; do | |
| sudo route -n add -net "$net" "$TUNIP" 2>/dev/null || true | |
| done | |
| echo "🚀 全局代理已开启,走 $PROXY_HOST:$PROXY_PORT" | |
| } | |
| function stop_proxy() { | |
| resolve_hosts | |
| # 删除全局路由 | |
| for net in "${NETS[@]}"; do | |
| sudo route -n delete -net "$net" "$TUNIP" 2>/dev/null || true | |
| done | |
| # 删除上游直连(用 REMOTE_HOSTS 解析到的 IP) | |
| for ip in "${RESOLVED_IPS[@]}"; do | |
| sudo route -n delete -host "$ip" 2>/dev/null || true | |
| done | |
| # 结束 tun2socks | |
| if [[ -f /tmp/tun2socks.pid ]]; then | |
| kill -9 $(cat /tmp/tun2socks.pid) 2>/dev/null || true | |
| rm /tmp/tun2socks.pid | |
| fi | |
| killall tun2socks 2>/dev/null || true | |
| # 关掉 TUN | |
| sudo ifconfig "$DEV" down 2>/dev/null || true | |
| echo "🛑 全局代理已关闭" | |
| } | |
| case "$1" in | |
| start) start_proxy ;; | |
| stop) stop_proxy ;; | |
| restart) stop_proxy; start_proxy ;; | |
| *) echo "用法: $0 {start|stop|restart}" ;; | |
| esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment