經過一番調試,發現當網線熱插拔時,系統並沒有觸發鏈路斷開事件通知netifd進程來關閉網絡,導致其接口的配置殘留在路由表中,從而影響其他接口搜索默認網關。
根本原因是MT7628系列設備具有內置交換機功能,由於交換機和CPU端口之間始終連接,因此本地以太網接口永遠不會看到鏈路斷開事件,這意味着netifd將不會關閉並取消配置關聯的網絡,導致熱插拔無效。
解決方法
既然是硬件原因導致無法使用熱插拔事件,那只好通過輪詢方式來檢測網絡。定期對外網進行ping測試,如果測試正常,則無需切換網絡;如果測試失敗,則自動切換到另一個網絡接口,以此循環。通過以下腳本,能實現網絡接口的動態切換。
1.網絡測試及切換腳本
通過以下腳本,可以實現周期ping測試和網絡接口切換功能。
腳本名稱:/etc/pingtest
#!/bin/sh state=0 IP="www.baidu.com" ping_status() { for var in 1 2 3; do if ping -c 1 $IP > /dev/null; then #echo "$IP Ping is successful." return 0 else #echo "$IP Ping is failure" if [ $var -eq 3 ]; then return 1 fi fi done } while true do ping_status if [ $? -ne 0 ]; then case $state in 0) #echo "wan to wwan" if uci get network.wwan > /dev/null; then uci set network.wwan.metric=0 fi if uci get network.wan > /dev/null; then uci set network.wan.metric=20 fi if uci get network.4G > /dev/null; then uci set network.4G.metric=10 fi ;; 1) #echo "wwan to 4G" if uci get network.wwan > /dev/null; then uci set network.wwan.metric=20 fi if uci get network.wan > /dev/null; then uci set network.wan.metric=10 fi if uci get network.4G > /dev/null; then uci set network.4G.metric=0 fi ;; 2) #echo "4G to wan" if uci get network.wwan > /dev/null; then uci set network.wwan.metric=10 fi if uci get network.wan > /dev/null; then uci set network.wan.metric=0 fi if uci get network.4G > /dev/null; then uci set network.4G.metric=20 fi ;; esac uci commit network; /etc/init.d/network reload; let state++ if [ ${state} -ge 3 ]; then state=0 fi fi sleep 10 done
-
進行對外網進行一輪ping測試,最多測試3次,當有一次測試通過則代表成功,不作網絡處理;如果3次測試失敗,則表示網絡已斷。
-
如果網絡已斷,通過UCI命令修改network文件中各接口的默認網關優先級參數metric(值越小優先級越高),使用uci commit network命令保存修改,並重新加載配置文件:/etc/init.d/network reload。
-
完成一輪檢測后,10秒后再次檢測,以此循環。如果當前使用的網絡接口斷了,腳本就會自動切換到適合的下一個網絡接口。
2.開機自啟腳本
在/etc/init.d/目錄下編寫開機啟動的shell腳本,該腳本運行時,在后台啟動/etc/pingtest腳本。
腳本名稱:/etc/init.d/interface_check
#!/bin/sh /etc/rc.common START=98 STOP=99 USE_PROCD=1 start_service() { procd_open_instance procd_set_param respawn . /etc/pingtest & procd_close_instance } stop_service() { return; }
-
START=98,STOP=99分別是啟動和關閉和優先級
-
USE_PROCD=1表示使用進程,配合procd_open_instance和
procd_close_instance命令啟動新進程,讓/etc/pingtest腳本在進程中運行。
3.開啟啟動腳本軟鏈接
在/etc/rc.d目錄下新建開機啟動腳本/etc/init.d/interface_check的軟鏈接,下次開機腳本就會自動運行。
ln -s /etc/init.d/interface_check /etc/rc.d/S98interface_check
S98是腳本啟動的優先級
鏈接:https://www.jianshu.com/p/f058229a42d8