Linux双网卡策略路由需配置多路由表与规则:一、基于源地址绑定路由表并设优先级;二、基于入接口指定路由表;三、用ip rule优先级控制匹配顺序;四、通过网络脚本持久化配置;五、用ip route get等命令验证路径。

如果您在Linux系统中配置了双网卡,但发现流量未按预期路径转发,可能是由于内核仅维护单一默认路由表,无法区分不同网卡的出向策略。以下是实现双网卡策略路由的多种配置方法:
一、基于源地址的策略路由
该方法通过为不同网卡绑定独立的路由表,并依据数据包的源IP地址决定使用哪张路由表,从而实现入向与出向路径一致性。
1、为eth0网卡创建专用路由表,在/etc/iproute2/rt_tables末尾添加:100 table_eth0
2、为eth1网卡创建专用路由表,在同一文件中添加:101 table_eth1
3、为table_eth0添加默认路由(假设eth0网关为192.168.1.1):ip route add default via 192.168.1.1 dev eth0 table table_eth0
4、为table_eth1添加默认路由(假设eth1网关为10.0.2.1):ip route add default via 10.0.2.1 dev eth1 table table_eth1
5、添加源地址匹配规则:对来自192.168.1.0/24网段的流量启用table_eth0:ip rule add from 192.168.1.0/24 table table_eth0
6、对来自10.0.2.0/24网段的流量启用table_eth1:ip rule add from 10.0.2.0/24 table table_eth1
二、基于入接口的策略路由
该方法依据数据包进入系统的网络接口决定其后续路由行为,适用于需要严格分离内外网流量的场景,尤其在防火墙或网关设备中常见。
1、清空现有规则中与入接口相关的条目(如有):ip rule del to 0.0.0.0/0 iif eth0
2、为从eth0进入的数据包指定使用table_eth0:ip rule add to 0.0.0.0/0 iif eth0 table table_eth0
3、为从eth1进入的数据包指定使用table_eth1:ip rule add to 0.0.0.0/0 iif eth1 table table_eth1
4、确保对应路由表中包含直连子网路由(如eth0连接192.168.1.0/24):ip route add 192.168.1.0/24 dev eth0 src 192.168.1.100 table table_eth0
5、同理添加eth1直连网段:ip route add 10.0.2.0/24 dev eth1 src 10.0.2.100 table table_eth1
三、使用ip rule优先级控制路由顺序
当存在多条匹配规则时,内核按rule优先级(priority值)从小到大依次匹配,合理设置优先级可避免规则冲突或覆盖。
1、查看当前所有规则及其优先级:ip rule show
2、为eth0源地址规则设置高优先级(例如100):ip rule add from 192.168.1.0/24 table table_eth0 priority 100
3、为eth1源地址规则设置次高优先级(例如101):ip rule add from 10.0.2.0/24 table table_eth1 priority 101
4、为默认回退路由设置最低优先级(例如32766):ip rule add to 0.0.0.0/0 table main priority 32766
5、删除重复或冲突的旧规则(如已有相同from地址的规则):ip rule del from 192.168.1.0/24
四、持久化策略路由配置
重启后临时配置将丢失,需将策略路由写入系统启动脚本或网络管理服务配置中,确保每次开机自动加载。
1、在RHEL/CentOS系中,编辑/etc/sysconfig/network-scripts/rule-eth0,写入:from 192.168.1.0/24 table table_eth0
2、编辑/etc/sysconfig/network-scripts/route-eth0,写入:default via 192.168.1.1 dev eth0 table table_eth0
3、在Debian/Ubuntu系中,修改/etc/network/interfaces,在eth0节下添加:post-up ip rule add from 192.168.1.0/24 table table_eth0
4、同样在eth0节下添加:post-up ip route add default via 192.168.1.1 dev eth0 table table_eth0
5、验证持久化脚本是否具备执行权限:chmod +x /etc/network/if-up.d/your-routing-script
五、验证与排错命令集
策略路由生效后,必须通过多维度验证确保各网卡路径独立且无交叉,避免因路由环路或黑洞导致通信中断。
1、查看当前所有策略规则:ip rule list
2、查看table_eth0中的完整路由条目:ip route show table table_eth0
3、查看table_eth1中的完整路由条目:ip route show table table_eth1
4、模拟从特定源IP发起连接,观察实际走哪条路径:ip route get 8.8.8.8 from 192.168.1.100
5、检查ARP缓存是否已更新对应网关MAC:ip neigh show | grep -E "(192\.168\.1\.1|10\.0\.2\.1)"










