多IP环境下 指定某个目的IP地址通过某个本地IP访问 策略路由
需求
在CentOS 7.9中,若需从特定源IP(10.0.0.3)访问目标网段 1.1.1.0/24
方法一:策略路由(支持网段)
1. 创建自定义路由表
# 添加名为custom_table的路由表(ID=200)
echo "200 custom_table" >> /etc/iproute2/rt_tables
2. 向路由表添加默认路由
# 替换10.0.0.254为实际网关(通过ip route show default查看)
ip route add default via 10.0.0.254 dev eth0 table custom_table
3. 设置策略路由规则
# 匹配目标网段1.1.1.0/24,强制使用custom_table路由表
ip rule add to 1.1.1.0/24 lookup custom_table
4. 绑定源IP到路由表
# 指定从该路由表发出的流量源IP为10.0.0.3
ip route add default via 10.0.0.254 dev eth0 src 10.0.0.3 table custom_table
5. 持久化配置
# 创建规则文件(目标网段+路由表)
echo "to 1.1.1.0/24 lookup custom_table" > /etc/sysconfig/network-scripts/rule-eth0
# 创建路由表文件(包含源IP配置)
echo "default via 10.0.0.254 dev eth0 src 10.0.0.3" > /etc/sysconfig/network-scripts/route-custom_table
方法二:iptables SNAT(支持网段)
1. 添加SNAT规则
# 匹配目标网段1.1.1.0/24,修改源IP为10.0.0.3
iptables -t nat -A OUTPUT -d 1.1.1.0/24 -j SNAT --to-source 10.0.0.3
2. 保存规则
# 保存规则并重启服务(需安装iptables-services)
iptables-save > /etc/sysconfig/iptables
systemctl restart iptables
方法三
1. 使用1.1.1.1的网关:
ip route add 移动IP段1 via 移动网关 src 移动IP
ip route add 移动IP段2 via 移动网关 src 移动IP
ip route add 移动IP段3 via 移动网关 src 移动IP
验证配置
方法一验证
# 查看策略规则
ip rule show | grep "1.1.1.0/24"
# 应输出:32765: from all to 1.1.1.0/24 lookup custom_table
# 测试流量源IP(使用tcpdump抓包)
tcpdump -i eth0 src 10.0.0.3 and dst 1.1.1.0/24
方法二验证
# 查看NAT规则
iptables -t nat -L -n -v
# 应包含:SNAT all -- * * 0.0.0.0/0 1.1.1.0/24 to:10.0.0.3
# 测试连通性
curl --connect-timeout 5 http://1.1.1.1
注意事项
1. 网关一致性
确保所有命令中的网关(10.0.0.254)与实际网络一致,可通过以下命令查询:
ip route show default | awk '/default/ {print $3}'
2. 策略路由优先级
若系统已有其他路由规则,可通过调整优先级(priority参数)确保新规则生效:
ip rule add to 1.1.1.0/24 lookup custom_table priority 1000
3. 防火墙冲突
如果使用firewalld,需关闭或配置兼容规则:
systemctl stop firewalld && systemctl disable firewalld
4. 永久生效
策略路由需确保rule-eth0和route-custom_table文件权限为644。
iptables规则需安装iptables-services并启用:
yum install iptables-services
systemctl enable iptables
版权声明:
作者:三炮不吃鱼
链接:https://www.keke.moe/archives/2540.html
文章版权归作者所有,未经允许请勿转载。
THE END