集群IPtables转发与防火墙

子网集群通过接入公网的服务器Iptables转发上网

1. 对iptables进行初始化工作

清空filter表

iptables -F

清空nat表

iptables -t nat -F

默认禁止所有传入连接

iptables -P INPUT DROP

默认允许所有传出连接

iptables -P OUTPUT ACCEPT

默认禁止路由转发

iptables -P FORWARD DROP

2.打开系统的IP转发功能
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf

不用重启,立即生效

sysctl -p

3. 配置iptables的传入连接

允许环回接口的传入连接

iptables -A INPUT -i lo -j ACCEPT

允许已建立的传入连接

iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT

允许SSH传入连接

iptables -A INPUT -i eno1  -p tcp –dport 22 -j ACCEPT       根据自己外网网卡配置

4. 配置iptables的NAT转发---实现子网上网

允许来自内网的传出连接

iptables -A FORWARD -s 192.168.10.0/24 -j ACCEPT

开启源NAT功能
即将来自内网主机的IP转换为外网IP。

iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j SNAT –to 【公网ip】

5. 端口转发

通过端口转发实现子网内服务器特定端口对外服务功能

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 【公网端口】 -j DNAT --to-destination 【内网IP】: 指定子网服务器端口

eg:iptables -t nat -A PREROUTING -p tcp -m tcp --dport 8001 -j DNAT --to-destination 172.31.2.51:22  将公网8001端口转向子网特定服务器22端口

如上实现则为所有客户端均可访问,若要指定ip可以访问则需要

iptables -t nat -A PREROUTING 【指定IP地址】-p tcp -m tcp --dport 【公网端口】 -j DNAT --to-destination 【内网IP】: 指定子网服务器端口

6.禁止访问

如果需要禁止某些ip访问端口则可以在filter中添加规则

iptables -I INPUT -p tcp --dport 8001 -j DROP    禁止所有访问该端口的请求

iptables -A INPUT -p tcp --dport 8001 -j ACCEPT  开启同理

允许特定ip访问特定端口则可仅对特定IP开放端口

-A INPUT -s 【特定ip】 -p tcp -m tcp --dport 8001 -j ACCEPT

iptables注意事项

使用指令iptables +xxxxxx会将iptables规则写入内存,重启iptables失效

如果想要把配置保存起来,可以执行 service iptables save 
这样就不会每次重启 iptables 的时候配置就失效了。

当/etc/sysconfig/iptables 内容与内存中不一致时,重启iptables会出现错误,需要先保存在重启,重启读取的是/etc/sysconfig/iptables中的配置文件。

不要随便禁用22端口,保证ssh可以正常运行,可以省去很多麻烦

猜你喜欢

转载自www.cnblogs.com/freedom314/p/9258730.html