场景
在CentOS 在进行带宽汇聚时,需要将默认路由设置为其他ip 时用得到
以下代码仅适用于 CentOS7
其他系统未进行测试
__set_manage_route_table() {
# 设置管理线路的路由表
_is=$(ip route list table 252-manage | grep default -c)
if ((_is != 1)); then
if (($(grep '252-manage' -c </etc/iproute2/rt_tables) == 0)); then echo '252 252-manage' >>/etc/iproute2/rt_tables; fi
_nic=$(ip r | grep -v -E 'ppp|docker|br|eth9|vnic' | grep -E '(^default)|(\ssrc\s)' | grep -o 'dev\s\S*' | awk '{print $NF}' | head -1)
_subnet=$(ip r | grep "$_nic" | grep '.*/\S*\sdev' | head -1 | awk '{print $1}')
_gateway=$(ip r | grep "default.* dev\s$_nic" | head -1 | awk '{print $3}')
if [[ "${_gateway}" == "" ]]; then
_gateway=$(cat /etc/sysconfig/network-scripts/ifcfg-"$_nic" | grep -i 'GATEWAY' | awk -F '=' '{print $NF}' | grep -Eo '[0-9.]{1,16}')
fi
echo "$_nic $_subnet $_gateway"
if [[ "$_subnet" != "" && "$_gateway" != "" ]]; then
ip rule del lookup 252-manage 2>/dev/null
ip rule add from "$_subnet" table 252-manage
ip route flush table 252-manage
ip route add default via "$_gateway" table 252-manage
ip route list table 252-manage
echo 'table set'
fi
fi
}
__set_manage_route_table
__set_manage_route_table() {
# 设置管理线路的路由表
_is_rt_tables=$(grep "252-manage" -c </etc/iproute2/rt_tables)
if ((_is_rt_tables == 0)); then
echo -e "252\t252-manage" >>/etc/iproute2/rt_tables
fi
_nic=$(ip r | grep -E '^default' | grep -v -E 'ppp|docker|br|eth9|vnic' | grep -o 'dev\s\S*' | awk '{print $NF}' | head -1)
_subnet=$(ip r | grep "$_nic" | grep -E '^[0-9]{1,3}\..*\sdev' | head -1 | awk '{print $1}')
_gateway=$(ip r | grep "^default.* via.*dev\s$_nic" | head -1 | awk '{print $3}')
if [[ "${_gateway}" == "" ]]; then
_gateway=$(grep -Ei '^GATEWAY' </etc/sysconfig/network-scripts/ifcfg-"$_nic" | awk -F '=' '{print $NF}' | grep -Eo '[0-9.]{1,16}')
fi
echo "$_nic $_subnet $_gateway"
_is=$(ip route list table 252-manage | grep "default.*$_nic" -c)
if ((_is != 1)); then
if [[ "$_nic" != "" && "$_subnet" != "" && "$_gateway" != "" ]]; then
ip rule del lookup 252-manage 2>/dev/null
ip rule add from "$_subnet" table 252-manage
ip route flush table 252-manage
ip route add default via "$_gateway" table 252-manage
ip route list table 252-manage
echo 'table set'
fi
fi
}
上面的代码起到一个什么样的作用
- 设置路由表
- 添加规则
- 路由表上的默认路由