CentOS系统中使用iptables设置端口转发(SS国内中转)
大家熟知的Haproxy也是可以设置端口转发的,但Haproxy无法转发udp数据,所以这次使用iptables来转发tcp和udp的数据。实话说,iptables这个命令,还是很有用处的,在linux下,到处都可以看到这个命令,而CentOS系统就更不用说了!
清空相关规则
首先我们需要加载相关的内核模块:
/sbin/modprobe ip_tables
/sbin/modprobe ip_nat_ftp
/sbin/modprobe ip_conntrack_ftp
清除预设表 filter 中,所有规则链中的规则:
/sbin/iptables -F
清除nat表中,所有规则链中的规则
/sbin/iptables -F -t nat
清除预设表 filter 中,使用者自订链中的规则:
/sbin/iptables -X
将封包计数器归零,封包计数器是用来计算同一封包出现次数,是过滤阻断式攻击不可或缺的工具:
/sbin/iptables -Z
清除mangle表中,所有规则链中的规则:
iptables -F -t mangle
清除mangle表中,使用者自订链中的规则:
iptables -t mangle -X
清除nat表中,使用者自订链中的规则:
iptables -t nat -X
定义链的规则(设定预设规则):
/sbin/iptables -P INPUT ACCEPT
/sbin/iptables -P FORWARD DROP
/sbin/iptables -P OUTPUT ACCEPT
打开 forward 功能 (或在/etc/sysconfig/network 中添加 FORWARD_IPV4=yes 打开转发功能,实现各网段互访):
echo "1"> /proc/sys/net/ipv4/ip_forward
配置iptables转发
iptables -t nat -A POSTROUTING -j MASQUERADE
iptables -A FORWARD -s 1.1.1.1 -j ACCEPT
iptables -t nat -A PREROUTING -p tcp --dport 10000:20000 -j DNAT --to-destination 1.1.1.1:10000-20000
iptables -t nat -A PREROUTING -p udp --dport 10000:20000 -j DNAT --to-destination 1.1.1.1:10000-20000
iptables -t nat -A POSTROUTING -p tcp -d 1.1.1.1 --dport 10000:20000 -j SNAT --to-source 2.2.2.2
iptables -t nat -A POSTROUTING -p udp -d 1.1.1.1 --dport 10000:20000 -j SNAT --to-source 2.2.2.2
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
然后继续下面的操作:
重要说明 from www.mfbuluo.com
1.1.1.1 为目标服务器的IP地址
10000:20000 需要转发的端口范围
2.2.2.2 本机服务器的IP(也就是中转机)
最后面两条是ssh的端口,根据你自己使用的ssh端口进行添加
然后保存和重启iptables以及添加开机启动
保存:service iptables save
重启:service iptables restart
开机启动:chkconfig iptables on
iptables转发的配置也就这么多,大家可以用自己的阿里云或者腾讯云尝试!