将一个服务器当做另一个服务器的代理
utils
本文字数:576 字 | 阅读时长 ≈ 2 min

将一个服务器当做另一个服务器的代理

utils
本文字数:576 字 | 阅读时长 ≈ 2 min

服务器代理设置方案

本文介绍两种在 Linux 上设置代理的方法:基础的 SSH 隧道方案和使用 Surge 的进阶方案。

方案一:基础 SSH 隧道

前置准备

  1. 确保本地机器已安装 SSH
    # Ubuntu/Debian 安装 SSH
    sudo apt-get install openssh-server
    
  2. 确保远程服务器已安装并运行 SSH 服务

设置步骤

  1. 创建 SSH 隧道

    ssh -D 8080 -f -C -q -N user@your_remote_server.com
    

    参数说明:

    • -D 8080: 指定本地端口
    • -f: 后台运行
    • -C: 启用压缩
    • -q: 静默模式
    • -N: 不执行远程命令
  2. 配置系统代理

    # 添加到 ~/.bashrc 或 ~/.bash_profile
    export http_proxy="socks5://localhost:8080"
    export https_proxy="socks5://localhost:8080"
    
  3. 应用配置

    source ~/.bashrc  # 或 source ~/.bash_profile
    

方案二:Surge + SSH 反向隧道(适用于阿里云访问 Google)

方案概述

  1. 阿里云服务器通过 SSH 反向隧道连接到 Mac
  2. 阿里云服务器的流量经过 SSH 隧道到达 Mac
  3. Mac 运行 Surge 代理 Google 流量

详细步骤

  1. 在 Mac 上创建 SSH 反向隧道

    ssh -R 6152:127.0.0.1:6152 -R 6153:127.0.0.1:6153 root@阿里云服务器IP
    
  2. 在阿里云服务器配置代理

    export http_proxy="http://127.0.0.1:6152"
    export https_proxy="http://127.0.0.1:6152"
    export ALL_PROXY="socks5h://127.0.0.1:6153"
    

优化建议

  1. 后台运行 SSH 隧道

    ssh -R 6152:127.0.0.1:6152 -R 6153:127.0.0.1:6153 -N -f root@阿里云服务器IP
    
  2. 使用 autossh 自动重连

    brew install autossh
    autossh -R 6152:127.0.0.1:6152 -R 6153:127.0.0.1:6153 -N -f root@阿里云服务器IP
    
  3. 配置 SSH 持久连接

    ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -R 6152:127.0.0.1:6152 -R 6153:127.0.0.1:6153 -N -f root@阿里云服务器IP
    

故障排查

  1. 检查端口监听状态

    netstat -tlnp | grep 6152
    netstat -tlnp | grep 6153
    
  2. 测试代理连接

    curl -x http://127.0.0.1:6152 -I https://www.google.com
    
  3. 手动指定 DNS

    curl --resolve www.google.com:443:142.250.190.4 -x http://127.0.0.1:6152 -I https://www.google.com
    

方案对比

方案 适用情况 复杂度 可靠性
SSH 反向隧道 + Surge 代理 最简单,适合 Mac 能 SSH 连接阿里云 ⭐⭐⭐
Tailscale / ZeroTier VPN 适合长期使用,安全 ⭐⭐ ⭐⭐⭐⭐
Cloudflare Tunnel 适合不想暴露端口 ⭐⭐⭐ ⭐⭐⭐⭐⭐

推荐方案

4月 06, 2025
3月 10, 2025
12月 31, 2024