一、背景

在日常运维或科研计算中,我们经常遇到远程服务器无法直接访问外网的情况,例如:

  • 服务器所在网络环境有防火墙限制
  • 服务器没有公网 IP 或被限制访问外部 HTTP/HTTPS 资源

此时,可以利用 本地机器的外网网络,通过 SSH 反向端口转发 + HTTP 代理(tinyproxy),让远程服务器“借道”本地网络访问互联网。


二、原理

整体思路如下:

  1. 本地机器运行 tinyproxy,监听 8888 端口,提供 HTTP 代理服务
  2. SSH 反向隧道将远程服务器的 localhost:8888 映射到本地的 8888 端口
  3. 远程服务器设置 http_proxy / https_proxy 环境变量,让 HTTP 请求通过本地代理出网

三、安装与配置

1. 本地机器安装 tinyproxy

1
sudo apt install tinyproxy

2. 启动 tinyproxy 服务

1
sudo systemctl start tinyproxy

默认会监听 8888 端口,可用以下命令验证:

1
sudo lsof -i:8888

如果输出类似:

1
tinyproxy  8993 tinyproxy  ... TCP *:8888 (LISTEN)

说明代理已启动。

3. 建立 SSH 反向隧道

本地机器执行:

1
ssh -R 8888:localhost:8888 [email protected]

说明:

  • -R 8888:localhost:8888:将远程服务器的 8888 端口映射到本地的 8888 端口
  • [email protected]:远程服务器的登录用户和 IP

4. 在远程服务器配置代理环境变量

SSH 登录到远程服务器后:

1
2
3
echo 'export http_proxy=http://localhost:8888' >> ~/.bashrc
echo 'export https_proxy=http://localhost:8888' >> ~/.bashrc
source ~/.bashrc

这样每次登录都会自动加载代理配置。


四、测试

在远程服务器上执行:

1
curl -I https://baidu.com

输出结果:

1
2
3
4
5
6
7
8
9
10
HTTP/1.0 200 Connection established
Proxy-agent: tinyproxy/1.11.0

HTTP/1.1 302 Moved Temporarily
Server: bfe/1.0.8.18
Date: Mon, 04 Aug 2025 01:58:38 GMT
Content-Type: text/html
Content-Length: 161
Connection: keep-alive
Location: http://www.baidu.com/

解释:

  • HTTP/1.0 200 Connection established:tinyproxy 已成功连接目标服务器
  • HTTP/1.1 302 Moved Temporarily:百度返回了正常的跳转响应(将 https://baidu.com 重定向到 http://www.baidu.com

五、注意事项

  1. tinyproxy 只能代理 HTTP/HTTPS 流量ping 等 ICMP 请求不会走代理

  2. 要验证代理是否真的生效,可以用:

    1
    curl -x http://localhost:8888 https://ipinfo.io/ip

    返回的应是本地机器的公网 IP,而不是远程服务器的 IP

  3. 如果需要让所有协议(包括 ping、SSH 等)都走代理,可以考虑改用 socks5 全局代理 或 VPN 方案