其他分享
首页 > 其他分享> > SNAT和DNAT

SNAT和DNAT

作者:互联网

SNAT和DNAT

一、SNAT

1、SNAT原理和应用

应用环境:局域网主机共享单个公网IP地址接入Internet ( 私有IP不能在Internet中正常路由)

SNAT原理:修改数据包的源地址

SNAT转换前提条件:

1.局域网各主机已正确设置IP地址、子网掩码、默认网关地址
2. Linux网关开启IP路由转发

临时打开:

echo 1  > /proc/sys/net/ipv4/ip_forward
或者
sysctl   -w   net.ipv4_forward=1

永久打开:

vim  /etc/sysctl.conf
net.ipv4.ip_forward  = 1    #  写入配置文件中

2、SNAT转换

在这里插入图片描述
1、固定的公网ip

iptables  -t  nat  -A  POSTROUTING  -s  192.168.22.0/24  -o  ens33  -j  SNAT  --to-source  12.0.0.1-12.0.0.10

2、非固定的公网IP地址(共享动态ip地址)

iptables  -t  nat  -A  POSTROUTING -s 192.168.22.0/24  -o  -j  MASQUERADE

二、DNAT

DNAT转换前提条件:
1、局域网的服务器能够访问Internet
2、网关的外网地址有正确的DNS解析记录
3、Linux关开启IP路由转发

把从ens33进来的要访问web服务的数据包目的地址转换为192.168.80.11
iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 80 -j DNAT --to 192.168.80.11
或
iptables -t nat -A PREROUTING -i ens33-d 12.0.0.1 -p tcp --dport 80 -j DNAT--to-destination 192.168.80.11
	                         入站 外网网卡  外网IP                                              内网服务器IP

iptables -t nat -A PREROUTING -i ens33 -p tcp--dport 80 -j DNAT --to 192.168.80.11-192.168.80.20	                   

防火墙规则的备份和还原

导出(备份)所有表的规则
iptables-save > /opt/ipt. txt 

导入(还原)规则
iptables-restore < /opt/ipt.txt

将iptables规则文件保存在/etc/sysconfig/iptables 中,iptables服 务启动时会自动还原规则
iptables-save > /etc/sysconfig/ iptables

systemctl stop iptables   #停止iptables服务会清空掉所有表的规则
systemctl start iptables   # 启动iptables服务会自动还原/etc/sysconfig/iptables  中的规则

tcpdump抓包

tcpdump tcp -i ens33- t -s 0 -C 100 and dst port ! 22 and src net 192.168.1.0/24 -W ./target. cap

(1)tcp:ipicmparprarp和tcp、udp、icmp这些选项等都要放到第一个参数的位置,用来过滤数据报的类型

(2)-i ens33 :只抓经过接口ens33的包

(3)-t:不显示时间戳

(4)-s0:抓取数据包时默认抓取长度为68字节。加上-s0后可以抓到完整的数据包

(5)-c100:只抓取100个数据包

(6)dst port ! 22 :不抓取目标端口是22的数据包

(7)src net 192.168.1.0/24 :数据包的源网络地址为192.168.1.0/24

(8)-W ./target.cap :保存成cap文件,方便用ethereal (即wireshark)分析

标签:iptables,DNAT,SNAT,192.168,数据包,ens33
来源: https://blog.csdn.net/weixin_55609944/article/details/117279421