需求
在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