個人服務器上有兩個網卡,一張配置內網ip,一張是公網ip,如今想實現兩張網卡走兩個網關。bash
系統環境服務器
eth0 172.16.200.11/24 網關172.16.200.1(默認網關) eth1 158.247.117.2/24 網關158.247.117.1
# eth1的網絡配置 [root@lb-01 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1 DEVICE="eth1" BOOTPROTO="static" IPADDR=158.247.117.2 NETMASK=255.255.255.0 # 這個要 NETWORK=158.247.117.0 ROUTER=158.247.117.1 # 這個要 ONBOOT="yes" TYPE="Ethernet" USERCTL="yes" PEERDNS="yes" IPV6INIT="no" PERSISTENT_DHCLIENT="1"
# 寫到rc.local;重啓會自動加路由;rt_tables就是routing tables [root@lb-01 ~]# cat /etc/rc.d/rc.local #!/bin/bash touch /var/lock/subsys/local for interface_file in $(ls /etc/sysconfig/network-scripts/ifcfg-eth* | grep -v ifcfg-eth0) ;do . ${interface_file} prefix=$(ipcalc -p ${IPADDR} ${NETMASK} | awk -F= '{print $2}') tablenum=$(echo ${DEVICE} | sed 's/eth//g') if [ ${ONBOOT} != 'yes' ] ;then continue fi if ! grep "^${tablenum} ${DEVICE}$" /etc/iproute2/rt_tables >/dev/null ;then echo "${tablenum} ${DEVICE}" >>/etc/iproute2/rt_tables fi ip route add ${NETWORK}/${prefix} dev ${DEVICE} src ${IPADDR} table ${DEVICE} ip route add default via ${ROUTER} dev ${DEVICE} table ${DEVICE} ip rule add from ${IPADDR}/32 table ${DEVICE} ip rule add to ${IPADDR}/32 table ${DEVICE} done
[root@lb-01 ~]# chmod +x /etc/rc.d/rc.local # 賦予執行權限 [root@lb-01 ~]# bash /etc/rc.d/rc.local # 手動運行
# 查看路由,有兩條default就對了 [root@lb-01 ~]# ip route show table all | grep default default via 158.247.117.1 dev eth1 table eth1 default via 172.16.200.1 dev eth0
參考連接網絡
http://brainscraps.wikia.com/wiki/Setup_Gateway_Routing_On_Multiple_Network_Interfaceside