让云服务器使用本机代理访问外网
通过 SSH 反向端口转发,将本地代理共享给远程云服务器,解决服务器无法直接访问外网的问题。
让云服务器使用本机代理访问外网
场景
云服务器(如国内 VPS)无法直接访问 GitHub、npm 等外网资源,但你本地电脑有代理。 本文介绍如何通过 SSH 反向端口转发,让服务器借助本地代理上网。
约定:下文中
<PORT>代表本地代理端口,<USER>代表服务器登录用户名,<SERVER_IP>代表服务器 IP 地址。请根据实际情况替换。
原理
graph LR
A["本地电脑<br/>代理运行在 :PORT"] -- "SSH -R 反向转发" --> B["云服务器<br/>localhost:PORT"]
B -- "curl / git / npm ..." --> A
第 1 步:本地确认代理可用
在本地电脑执行:
1
curl -x http://127.0.0.1:<PORT> -I https://registry.npmjs.org
如果返回 HTTP/2 200,说明代理正常工作,继续下一步。
第 2 步:建立 SSH 反向端口转发
在本地电脑执行:
1
ssh -fN -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -R <PORT>:127.0.0.1:<PORT> <USER>@<SERVER_IP>
参数说明:
| 参数 | 作用 |
|---|---|
-f | 后台运行 |
-N | 不执行远程命令,仅做端口转发 |
-o ServerAliveInterval=60 | 每 60 秒发送心跳,防止连接断开 |
-o ServerAliveCountMax=3 | 最多容忍 3 次无响应后断开 |
-R <PORT>:127.0.0.1:<PORT> | 将服务器的 <PORT> 端口转发到本地的代理端口 |
注意:如果报
remote port forwarding failed,说明服务器 SSH 禁用了反向转发。需要管理员在服务端/etc/ssh/sshd_config中开启:
1 AllowTcpForwarding yes修改后重启 SSH 服务:
sudo systemctl restart sshd
然后正常登录服务器:
1
ssh <USER>@<SERVER_IP>
第 3 步:服务器上验证代理转发
在服务器上执行:
1
curl -x http://127.0.0.1:<PORT> -I https://registry.npmjs.org
如果返回 HTTP/2 200,说明服务器已经能通过本地代理访问外网。
第 4 步:设置 Shell 代理环境变量
在服务器上执行:
1
2
3
4
export http_proxy=http://127.0.0.1:<PORT>
export https_proxy=http://127.0.0.1:<PORT>
export HTTP_PROXY=http://127.0.0.1:<PORT>
export HTTPS_PROXY=http://127.0.0.1:<PORT>
提示:以上设置仅对当前 Shell 会话有效,关闭终端后即失效。如需持久化,可将上述
export命令追加到~/.bashrc或~/.zshrc中:
1 2 3 4 5 6 echo ' export http_proxy=http://127.0.0.1:<PORT> export https_proxy=http://127.0.0.1:<PORT> export HTTP_PROXY=http://127.0.0.1:<PORT> export HTTPS_PROXY=http://127.0.0.1:<PORT> ' >> ~/.bashrc && source ~/.bashrc
参考文献
本文由作者按照 CC BY 4.0 进行授权