我的主机有 ETH0、ETH1 作为 WAN 接口,WLAN0 作为客户端接口。主机本身的默认路由是 eth0。我需要将所有 nat 客户端路由到 eth1(伪装)。尝试使用 iptables mangle(预路由)标记数据包 - 没有帮助。
有人知道怎么做吗?
答案1
你可能根本不需要标记数据包。如果你只想根据源地址路由数据包,你可以简单地执行以下操作:
ip rule add from clients_subnet/mask tab 1 priority 500
ip route add default via second_gateway_ip dev eth1 tab 1
这将导致所有来自的数据包都clients_subnet/mask
通过 eth1 接口转发second_gateway_ip
。所有其他流量将通过默认网关转发(假设没有定义其他规则)。
要进行 NAT,您只需执行以下操作:
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
答案2
抱歉,这里有更多详细信息:
这是测试环境。主机有 2 个接口:ens160 作为主 WAN,tun-test 作为连接到 ens192 的 NAT 客户端的 WAN 接口。
root@ubuntu-16:/# ifconfig
ens160 Link encap:Ethernet HWaddr 00:50:56:85:f7:ec
inet addr:118.211.160.13 Bcast:118.211.160.15 Mask:255.255.255.248
inet6 addr: fe80::250:56ff:fe85:f7ec/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6454 errors:0 dropped:11 overruns:0 frame:0
TX packets:743 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:421765 (421.7 KB) TX bytes:117602 (117.6 KB)
ens192 Link encap:Ethernet HWaddr 00:50:56:85:c0:c6
inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::250:56ff:fe85:c0c6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:5544 errors:0 dropped:3 overruns:0 frame:0
TX packets:39 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:342182 (342.1 KB) TX bytes:3238 (3.2 KB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:160 errors:0 dropped:0 overruns:0 frame:0
TX packets:160 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:11840 (11.8 KB) TX bytes:11840 (11.8 KB)
tun-test Link encap:IPIP Tunnel HWaddr
inet addr:192.168.100.2 P-t-P:192.168.100.2 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MTU:1480 Metric:1
RX packets:4 errors:0 dropped:0 overruns:0 frame:0
TX packets:4 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:336 (336.0 B) TX bytes:336 (336.0 B)
root@ubuntu-16:/# ip rule
0: from all lookup local
500: from 192.168.1.0/24 lookup 10
32766: from all lookup main
32767: from all lookup default
root@ubuntu-16:/# ip route show table 10
default via 192.168.100.1 dev tun-test
root@ubuntu-16:/# sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1
root@ubuntu-16:/# iptables-save
# Generated by iptables-save v1.6.0 on Wed Mar 1 12:13:29 2017
*nat
:PREROUTING ACCEPT [135:8626]
:INPUT ACCEPT [110:6610]
:OUTPUT ACCEPT [8:704]
:POSTROUTING ACCEPT [7:620]
-A POSTROUTING -o tun-test -j MASQUERADE
COMMIT
# Completed on Wed Mar 1 12:13:29 2017