场景
    在CentOS 在进行带宽汇聚时,需要将默认路由设置为其他ip 时用得到
    以下代码仅适用于 CentOS7
    其他系统未进行测试

    1. __set_manage_route_table() {
    2. # 设置管理线路的路由表
    3. _is=$(ip route list table 252-manage | grep default -c)
    4. if ((_is != 1)); then
    5. if (($(grep '252-manage' -c </etc/iproute2/rt_tables) == 0)); then echo '252 252-manage' >>/etc/iproute2/rt_tables; fi
    6. _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)
    7. _subnet=$(ip r | grep "$_nic" | grep '.*/\S*\sdev' | head -1 | awk '{print $1}')
    8. _gateway=$(ip r | grep "default.* dev\s$_nic" | head -1 | awk '{print $3}')
    9. if [[ "${_gateway}" == "" ]]; then
    10. _gateway=$(cat /etc/sysconfig/network-scripts/ifcfg-"$_nic" | grep -i 'GATEWAY' | awk -F '=' '{print $NF}' | grep -Eo '[0-9.]{1,16}')
    11. fi
    12. echo "$_nic $_subnet $_gateway"
    13. if [[ "$_subnet" != "" && "$_gateway" != "" ]]; then
    14. ip rule del lookup 252-manage 2>/dev/null
    15. ip rule add from "$_subnet" table 252-manage
    16. ip route flush table 252-manage
    17. ip route add default via "$_gateway" table 252-manage
    18. ip route list table 252-manage
    19. echo 'table set'
    20. fi
    21. fi
    22. }
    23. __set_manage_route_table
    1. __set_manage_route_table() {
    2. # 设置管理线路的路由表
    3. _is_rt_tables=$(grep "252-manage" -c </etc/iproute2/rt_tables)
    4. if ((_is_rt_tables == 0)); then
    5. echo -e "252\t252-manage" >>/etc/iproute2/rt_tables
    6. fi
    7. _nic=$(ip r | grep -E '^default' | grep -v -E 'ppp|docker|br|eth9|vnic' | grep -o 'dev\s\S*' | awk '{print $NF}' | head -1)
    8. _subnet=$(ip r | grep "$_nic" | grep -E '^[0-9]{1,3}\..*\sdev' | head -1 | awk '{print $1}')
    9. _gateway=$(ip r | grep "^default.* via.*dev\s$_nic" | head -1 | awk '{print $3}')
    10. if [[ "${_gateway}" == "" ]]; then
    11. _gateway=$(grep -Ei '^GATEWAY' </etc/sysconfig/network-scripts/ifcfg-"$_nic" | awk -F '=' '{print $NF}' | grep -Eo '[0-9.]{1,16}')
    12. fi
    13. echo "$_nic $_subnet $_gateway"
    14. _is=$(ip route list table 252-manage | grep "default.*$_nic" -c)
    15. if ((_is != 1)); then
    16. if [[ "$_nic" != "" && "$_subnet" != "" && "$_gateway" != "" ]]; then
    17. ip rule del lookup 252-manage 2>/dev/null
    18. ip rule add from "$_subnet" table 252-manage
    19. ip route flush table 252-manage
    20. ip route add default via "$_gateway" table 252-manage
    21. ip route list table 252-manage
    22. echo 'table set'
    23. fi
    24. fi
    25. }

    上面的代码起到一个什么样的作用

    1. 设置路由表
    2. 添加规则
    3. 路由表上的默认路由