iptables 设置端口转发

This commit is contained in:
light 2018-01-11 00:18:10 +08:00
parent 876721cd37
commit c76e301127
3 changed files with 84 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -0,0 +1,84 @@
# iptables 设置端口转发/映射
## 网络拓扑
![iptables_examples_network_topology](../static/img/iptables_examples_network_topology.png)
服务器A有两个网卡
内网ip192.168.1.3
外网ip10.138.108.103
本地回环:127.0.0.1
服务器B有网卡8001提供服务
内网ip192.168.1.1
## 目的
使用户通过外网10.138.108.1038001访问内网服务器192.168.1.1:8001
## 思路
![iptables_examples_network_topology](../static/img/iptables_frame.png)
如图2所示端口转发走的是下发A路利用nat表中prerouting做dnat用postrouting做snat
### 包分析
时期 |操作|源IP:PORT|目的IPPORT
------- |----|----|----
packet in|用户访问|1.2.3.4:5|10.138.108.103:8001
prerouting|dnat|1.2.3.4:5|192.168.1.1:8001
routing decision|判断是否转发|1.2.3.4:5|192.168.1.1:8001
postrouting|snat|10.138.108.103:X|192.168.1.1:8001
packet out|转发包|10.138.108.103:X|192.168.1.1:8001
## 开启内核ip转发
> nano /etc/sysctl.conf
将下项注释去掉
``` bash
# net.ipv4.ipv4_forward=1
```
## 脚本
``` bash
#!/bin/bash
pro='tcp'
src_host1='192.168.1.3'
src_host2='10.138.108.103'
src_port=8001
Dst_Host='192.168.1.1'
Dst_Port=8001
# 清空规则
iptables -F
iptables -X
iptables -Z
iptables -t nat -F
# Destination network address translate (dnat)
# 如图2所示
iptables -t nat -A PREROUTING -p $pro -d $src_host1 --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port
iptables -t nat -A PREROUTING -p $pro -d $src_host2 --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port
iptables -A FORWARD -p $pro -d $Dst_Host --dport $Dst_Port -j ACCEPT
# 本地连接不经过prerouting只经过output链所以想要在服务器A通过本地ip访问服务器B需要在output 链增加dnat规则
iptables -t nat -A OUTPUT -p $pro -d $src_host1 --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port
iptables -t nat -A OUTPUT -p $pro -d $src_host2 --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port
# source network address translate (snat)
iptables -t nat -A POSTROUTING -p $pro -d $Dst_Host --dport $Dst_Port -j SNAT --to $src_host1
# 显示已有规则
iptables -t nat -L -n --line-number
```