iptables实现服务器中转(ubuntu)
目录
实现中转
开启防火墙IPv4转发
echo -e "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p
单端口转发
iptables -t nat -A PREROUTING -p tcp --dport [本地端口] -j DNAT --to-destination [目标IP:目标端口]
iptables -t nat -A PREROUTING -p udp --dport [本地端口] -j DNAT --to-destination [目标IP:目标端口]
iptables -t nat -A POSTROUTING -p tcp -d [目标IP] --dport [目标端口] -j SNAT --to-source [本地服务器主网卡绑定IP]
iptables -t nat -A POSTROUTING -p udp -d [目标IP] --dport [目标端口] -j SNAT --to-source [本地服务器主网卡绑定IP]
例如:用2.2.2.2作为1.1.1.1的中继服务器
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 10000 -j DNAT --to-destination 1.1.1.1:10000
iptables -t nat -A PREROUTING -p udp -m udp --dport 10000 -j DNAT --to-destination 1.1.1.1:10000
iptables -t nat -A POSTROUTING -d 1.1.1.1 -p tcp -m tcp --dport 10000 -j SNAT --to-source 2.2.2.2
iptables -t nat -A POSTROUTING -d 1.1.1.1 -p udp -m udp --dport 10000 -j SNAT --to-source 2.2.2.2
保存配置
iptables-save > /etc/iptables.up.rules
开机加载
iptables-save > /etc/iptables.up.rules
echo -e '#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules' > /etc/network/if-pre-up.d/iptables
chmod +x /etc/network/if-pre-up.d/iptables
设置
查看规则
iptables -t nat -vnL POSTROUTING
iptables -t nat -vnL PREROUTING
删除规则
iptables -t nat -D POSTROUTING 1
iptables -t nat -D PREROUTING 1