把本地可用的Proxy代理服务器带到ssh远程服务器上

假如本地机器A在公司内网,可以通过代理服务器proxy.corp.com:8080科学上网。
ssh登录到阿里云的机器B,由于不在公司内网,默认情况下无法通过proxy.corp.com:8080科学上网。
这篇文章介绍,如何实现在机器B(阿里云的远程服务器)上,也能通过proxy.corp.com:8080科学上网。

1. 使用下面的脚本ssh登录阿里云的服务器B

1
2
3
4
5
6
7
8
9
#!/bin/bash
#>>> Author: Simon Huang
#>>> Mail: thelongestusernameofall@gmail.com
#>>> Created Time: Wed 25 Sep 2013 08:30:06 AM CST
expect -c "set timeout -1;
spawn -noecho ssh -R 8080:127.0.0.1:8080 username@aliyun-ip-address -p 2222;
expect *assword:*;
send user-password\r;
interact;";

这个命令不仅实现了ssh登录,还同时把本地的8080端口映射到了B机器(阿里云)的8080上。
这样在B机器上,所有往返8080端口的数据都会转发到A机器的8080端口上。

2. 在A机器上,将8080端口映射到proxy.corp.com:8080

2.1 安装haproxy

brew install haproxy

2.2 配置haproxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
global
log stdout format raw local0

defaults
mode http
option httplog
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms

frontend http_front
bind *:8080
default_backend http_back

backend http_back
server proxy_server proxy.corp.com:8080

注意上面的配置,只需要根据实际情况修改代理服务器地址(即proxy.corp.com:8080)即可。其他内容一般情况下不用改动。
将该内容保存到/usr/local/etc/haproxy.cfg (默认无此文件,新建即可)

2.3 启动haproxy

1
2
3
4
haproxy -f /usr/local/etc/haproxy.cfg

#注意该命令不会自动启动为服务或者到后台。ctrl-c快捷键或关掉shell即可杀死。
#当不需要代理时,杀死该进程即可。

3. 在B机器上(阿里云的远程服务器)上使用127.0.0.1:8080作为代理,即可。

1
2
3
4
5
export http_proxy=http://127.0.0.1:8080
export https_proxy=$http_proxy

#测试代理起作用
wget google.com