iptables常用场景及实例

in linux with 0 comment

iptables在实际企业应用的场景主要有以下三点:
1.linux的主机防火墙
2.局域网机器共享上网(表:NAT 链POSTROUTING)
3.外部地址和端口,映射为内部地址和端口(表:NAT 链:PREROUTING)

A 机器
网卡1 外网 外网IP
网卡2 内网 内网IP1

B 机器
网卡1 内网 内网IP2

如果想把公网端口P1 映射为内网B机器端口P2

#iptables -t nat -A PREROUTING -d [A公网地址] -p tcp -m tcp --dport [公网端口] -j DNAT --to-destination [B内网IP]:[B内网端口] #iptables -t nat -A POSTROUTING -d [B内网IP] -p tcp -m tcp --dport [B内网端口] -j SNAT --to-source [A内网地址] #iptables -A FORWARD -o [A内网网卡] -d [B内网IP] -p tcp --dport [B内网端口] -j ACCEPT #iptables -A FORWARD -i [A内网网卡] -s [B内网IP] -p tcp –sport [B内网端口] -j ACCEPT #iptables-save >/etc/iptables

在rc.local中加入

#iptables-restore

实现重启后自动加载

实例1:本机80端口的请求转发到8080端口。
#iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080

实例2:如果需要本机也可以访问,则需要配置OUTPUT链:
#iptables -t nat -A OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-ports 8080

实例3:两机之间的端口转发
#将本机的81端口的请求全部转发到192.168.1.1:80

#首先要启用ipv4的转发功能:

#echo 1 > /proc/sys/net/ipv4/ip_forward

#或者是修改/etc/sysctl.conf (via)以便重启后也会启用转发,然后设定iptables(via):

iptables -t nat -A PREROUTING -p tcp --dport 81 -j DNAT --to 192.168.1.1:80
iptables -t nat -A POSTROUTING -j MASQUERADE

#如果开启了防火墙功能,注意要将80和81两个端口都打开。

实例4:禁止Ping入
#允许内网(192.168.1.*)的ping入,允许ping出,禁止其它网段的ping入

#iptables -A INPUT -p icmp --icmp-type 8 -s 192.168.1.0/24 -j ACCEPT //本网段可以ping
#iptables -A INPUT -p icmp --icmp-type 8 -j DROP //全部禁ping

实例5:将内网服务器B,通过外网共享,达到内网B机器访问外网。
A服务器 外网ip eth0:192.168.101.30
内网ip eth1:192.168.213.30 网关 192.168.213.2 子网掩码:255.255.255.0
B服务器 内网ip eth0:192.168.213.40 网关 192.168.213.2或者192.168.213.30 子网掩码:255.255.255.0

1)首先保证FORWARD表 ACCEPT
#iptables -P FORWARD ACCEPT

2)开机ipv4转发功能
#echo "1" > /proc/sys/net/ipv4/ip_forward

3)保证B服务器的内网的网关为A服务器的内网IP.

4)A外网服务器设置nat网络共享
#iptables -t nat -A POSTROUTING -s 192.168.213.0/24 -o eth0 -j SNAT --to-source 192.168.101.30

或者使用
#iptables -t nat -A POSTROUTING -s 192.168.213.0/24 -o eth0 -j MASQUERADE

//MASQUERADE ip伪装,他的作用是,从服务器的网卡上,自动获取当前ip地址来做NAT。

Responses