在 Ubuntu 上使用 iptables 做 NAT(网络地址转换),通常分为 SNAT(出站 NAT) 和 DNAT(端口/入站映射) 两种场景。下面按常见用法说明。
NAT 依赖 Linux 的 IP 转发功能。
sysctl -w net.ipv4.ip_forward=1
编辑 /etc/sysctl.conf:
net.ipv4.ip_forward=1
然后执行:
sysctl -p
场景:
192.168.1.0/24eth01.2.3.4iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 1.2.3.4
用 MASQUERADE 更方便:
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
场景:
eth0192.168.1.100iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80
iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPT
# 开启转发
sysctl -w net.ipv4.ip_forward=1
# 清除旧规则(可选)
iptables -F
iptables -t nat -F
# SNAT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# 允许转发
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
apt install iptables-persistent
netfilter-persistent save
规则会保存到:
/etc/iptables/rules.v4
ip_forwardeth0 / ens33)FORWARD 链是否被 DROPiptables -t nat -L -n -v
iptables -t nat -D POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
如果你有 具体拓扑(几张网卡、IP 段、要做什么 NAT),我可以帮你写完整规则。