Linux作为网关iptables命令的使用
一.进行源地址转换
1.将系统改为默认,并且打开路由转发
  • echo 1 > /proc/sys/net/ipv4/ip_forward  
  • iptables -F  
  • iptables -t nat -F  
  • iptables -t mangle -F  
  • iptables -X  
  • iptables -t nat -X  
  • iptables -t mangle -X 
  • 2.源地址转发
    iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -i eth0 -j MASQUERADE
    二.目标地址转换
    1.一对一转换
    eth0 192.168.0.1  内网
    eth1 202.202.202.1 外网
    内网中一台主机 192.168.0.101
    现在要把外网访问202.202.202.1的所有流量映射到192.168.0.101上
  • iptables -t nat -A PREROUTING -d 202.202.202.1 -j DNAT --to-destination 192.168.0.101  
  • iptables -t nat -A POSTROUTING -d 192.168.0.101 -j SNAT --to 192.168.0.1 
  • 2.多对多转换
    eth0 192.168.0.1  内网
    eth1 202.202.202.1 、202.202.202.2 外网
    内网中2台主机 192.168.0.101、192.168.0.102
    现在要把外网访问202.202.202.1的所有流量映射到192.168.0.101上,同时把把外网访问202.202.202.2的所有流量映射到192.168.0.102上
    这里顺便提一下如何为网卡配置多个IP
    ifconfig eth1:1 202.202.202.2 netmask 255.255.255.0 up

  • iptables -t nat -A PREROUTING -d 202.202.202.1 -j DNAT --to-destination 192.168.0.101  
  • iptables -t nat -A POSTROUTING -d 192.168.0.101 -j SNAT --to 192.168.0.1  
  •   
  • iptables -t nat -A PREROUTING -d 202.202.202.2 -j DNAT --to-destination 192.168.0.102  
  • iptables -t nat -A POSTROUTING -d 192.168.0.102 -j SNAT --to 192.168.0.1
  • 3.一对多转换
    这个最常用,一般是内网或DMZ区内有多个应用服务器,可以将不同的应用流量映射到不同的服务器上
    环境:
    eth0 192.168.0.1  内网
    eth1 202.202.202.1  外网
    内网中2台主机 192.168.0.101(Web服务器)、192.168.0.102(邮件服务器)
    现在要把外网访问202.202.202.1的Web流量映射到192.168.0.101上,同时把把外网访问202.202.202.1的邮件访问流量映射到192.168.0.102上
  • iptables -t nat -A PREROUTING -d 202.202.202.1 -p tcp --dport 80 -j DNAT --to-destination 192.168.0.101:80  
  • iptables -t nat -A POSTROUTING -d 192.168.0.101 -p tcp --dport 80 -j SNAT --to 192.168.0.1  iptables -t nat -A PREROUTING -d 202.202.202.1 -p tcp --dport 25 -j DNAT --to-destination 192.168.0.102:25  
  • iptables -t nat -A POSTROUTING -d 192.168.0.102 -p tcp --dport 25 -j SNAT --to 192.168.0.1  iptables -t nat -A PREROUTING -d 202.202.202.1 -p tcp --dport 110 -j DNAT --to-destination 192.168.0.102:110  
  • iptables -t nat -A POSTROUTING -d 192.168.0.102 -p tcp --dport 110 -j SNAT --to 192.168.0.1 (iptables -t nat -A POSTROUTING -d 10.0.1.245 -j MASQUERADE)
  • 三.防火墙只允许使用某些端口
    1.只允许使用22端口
    iptables -A INPUT -s 10.0.0.2 -p tcp --dport 22 -j ACCEPT
    iptables -A OUTPUT -d 10.0.0.2 -p tcp --sport 22 -j ACCEPT
    2.不允许对80端口数据进行转发
    iptables -A FORWARD -s 192.168.0.0/24 -p tcp --dport 80 -j DROP
    更高级的应用(http://guodong810.blog.51cto.com/4046313/1097499 http://blog.csdn.net/bill_lee_sh_cn/article/details/4401896)
    删除规则:
     iptables -t nat --line-numbers -L
    iptables -t nat -D POSTROUTING 32