之前文章有介绍过,公司有服务器托管在IDC机房,并且在公司内部通过ssh搭建了SOCKS代理服务,实现通过代理服务器连接外地不同服务器目的(详情请查看此文《centos7下利用ssh做代理服务器》)。之前使用SOCKS代理都是通过在windows下安装Proxifier软件来实现访问不通地区服务器,走不同的代理的。但是直接在linux服务器上使用代理连接外地服务器就不是那么方便了。。这里研究了几天终于也实现了,特记录一下。
一、安装redsocks
1.1、下载地址
1 |
https://codeload.github.com/darkk/redsocks/zip/master |
1.2、redsocks安装需要依赖libevent-devel和gcc,所以需要提前安装。
1 |
[root@imzcy ~]# yum -y install libevent-devel gcc |
1.3、编译安装redsocks并复制其程序到指定目录(该目录下redsocks.conf.example为默认配置文件)
1 2 3 4 5 6 |
[root@imzcy ~]# unzip redsocks-master.zip [root@imzcy ~]# cd redsocks-master [root@imzcy redsocks-master]# make [root@imzcy redsocks-master]# cp redsocks /usr/bin/ [root@imzcy redsocks-master]# cd [root@imzcy ~]# |
二、编辑创建不同代理的redsocks配置文件,以实现访问不同地区服务器走不同代理
2.1. 创建浙江地区的配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[root@imzcy ~]# vi /etc/redsocks-zj.conf base { log_debug = off; log_info = on; log = stderr; daemon = off; redirector = iptables; } redsocks { local_ip = 127.0.0.1; local_port = 8881; ip = 192.168.1.2; port = 1080; type = socks5; } [root@imzcy ~]# |
2.2 创建深圳地区的代理配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[root@imzcy ~]# vi /etc/redsocks-sz.conf base { log_debug = off; log_info = on; log = stderr; daemon = off; redirector = iptables; } redsocks { local_ip = 127.0.0.1; local_port = 8882; ip = 192.168.1.2; port = 1081; type = socks5; } [root@imzcy ~]# |
配置文件详细介绍可以参考redsocks解压目录下默认配置文件redsocks.conf.example
base {}区域正常使用的话不需要改。
redsocks {}区域各配置项作用:
local_ip = 127.0.0.1; 定义本机运行的redsocks监听的地址
local_port = 8881; 定义redsocks监听端口(同时运行多个redsocks程序需要指定不同端口)
ip = 192.168.1.2; 定义代理服务器IP
port = 1080; 定义代理服务器端口
type = socks5; 定义类型为SOCKS5
三、开启多个screen窗口,以运行多个redsocks程序
1 2 3 4 5 |
[root@imzcy ~]# screen -S sz [root@imzcy ~]# /usr/bin/redsocks -c /etc/redsocks-sz.conf [root@imzcy ~]# screen -S zj [root@imzcy ~]# /usr/bin/redsocks -c /etc/redsocks-zj.conf |
四、定义防火墙规则,访问指定服务器IP段的连接都重定向到指定redsocks端口
1 2 3 4 |
[root@imzcy ~]# iptables -t nat -A OUTPUT -d 192.168.5.0/24 -p tcp -j REDIRECT --to-ports 8881 [root@imzcy ~]# iptables -t nat -A OUTPUT -d 192.168.6.0/24 -p tcp -j REDIRECT --to-ports 8882 [root@imzcy ~]# iptables -t nat -L -v --line-numbers //查看nat表规则 [root@imzcy ~]# iptables -t nat -D OUTPUT $编号 //删除指定编号的nat表OUTPUT链规则 |
五、直接使用ssh指定端口和用户密码连接对应服务器即可
1 2 3 4 5 6 7 8 |
[root@imzcy ~]# ssh -p 6666 zcy@192.168.5.3 zcy@192.168.5.3's password: Last login: Tue Sep 4 16:27:08 2018 from 192.168.5.3 [zcy@database ~]$ [zcy@database ~]$ exit logout Connection to 192.168.5.3 closed. [root@imzcy ~]# |