centos 添加DNAT SNAT

外网服务器IP 101.168.200.22 开放端口8310
内网服务器IP 192.168.55.72 开放端口8310

使访问外网101.168.200.22:8310的请求转发到内网192.168.55.72:8310

前题条件 打开服务器的端口转发
参考文章 [url=http://blog.csdn.net/michaelzhou224/article/details/16979285]sysctl命令及改变net.ipv4.ip_forward = 1方法[/url]
a临时打开
sysctl -w net.ipv4.ip_forward=1

echo 1 > /proc/sys/net/ipv4/ip_forward
b永久性打开
vi /etc/sysctl.conf
net.ipv4.ip_forward=1
sysctl -p

1、方式一
在centos服务器101.168.200.22上配置Iptable的DNAT和SNAT就可以完成转发
或者
若101.168.200.22为外网网关,在网关上配置端口映射,经过中间服务器192.168.55.1如
101.168.200.22:8310=======>192.168.55.1:8310==============>192.168.55.72:8310
则在192.168.55.1上作DNAT或SNAT,或者使用反向代理nginx


 #数据包中的目的 IP (路由器上的公网 IP) 将修改为内网 IP
# 请求路径101.168.200.22:8310============>192.168.55.72:8310
iptables -t nat -A PREROUTING -d 101.168.200.22 -p tcp --dport 8310 -j DNAT --to 192.168.55.72:8310

#SNAT:修改数据包的源ip(ip地址转换)
# 响应路径192.168.55.72:8310 ============>101.168.200.22:8310
iptables -t nat -A POSTROUTING -d 192.168.55.72 -p tcp --dport 8310 -j SNAT --to 101.168.200.22


2、方式二
101.168.200.22为网关,开放的101.168.200.22:8310端口,直接将该端口转发给192.168.55.72:8310
在101.168.200.22上配置
sysctl -w net.ipv4.ip_forward=1
iptables -I FORWARD -p tcp -j ACCEPT
iptables -I INPUT-p tcp -m state --state NEW -m tcp --dport 1521 -j ACCEPT
iptables -t nat -I PREROUTING -p tcp --dport 1521 -j DNAT --to 192.168.200.207
iptables -t nat -I POSTROUTING -p tcp --dport 1521 -j MASQUERADE
iptables -t nat -I PREROUTING -p tcp --dport 8310 -j DNAT --to 101.168.200.22
iptables -t nat -I POSTROUTING -p tcp --dport 8310 -j MASQUERADE


作成临时开放端口的脚本

#!/bin/sh

echo "please input oracle server ip"
read -p ":" ip
sysctl -w net.ipv4.ip_forward=1
iptables -I FORWARD -p tcp -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 1521 -j ACCEPT
iptables -t nat -I PREROUTING -p tcp --dport 1521 -j DNAT --to $ip
iptables -t nat -I POSTROUTING -p tcp --dport 1521 -j MASQUERADE
echo "================================================================"
echo "connection config success"
echo "please do not config iptables before the system status recover!"
echo "waiting to recover system status"
echo "================================================================"
echo "if your connection complete please input ok"
read -p ":" ok
sysctl -w net.ipv4.ip_forward=0
service iptables reload

你可能感兴趣的:(linux)