Ip

如果物理連接失去,請關閉網路介面

  • October 30, 2014

我有一個帶有兩個網卡的無頭 Debian 伺服器:

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
   link/ether 01:02:1d:54:7c:01 brd ff:ff:ff:ff:ff:ff
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
   link/ether 01:02:1d:54:7e:01 brd ff:ff:ff:ff:ff:ff

如果我斷開連接到 的電纜eth1,則埠將關閉,但在管理上它將保持正常:

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
   link/ether 01:02:1d:54:7c:01 brd ff:ff:ff:ff:ff:ff
2: eth1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT qlen 1000
   link/ether 01:02:1d:54:7e:01 brd ff:ff:ff:ff:ff:ff

這意味著與關聯eth1的路由仍然存在於路由表中。eth1一旦物理斷開,有沒有辦法強制行政關閉?

一個快速而骯髒的解決方案是使用ip monitor一個“ifupdowns”界面的腳本。

腳本將是:

#!/bin/sh

ip monitor link | while IFS=':' read num name status; do
   read extraline # iproute2 outputs physical address on a separate line.
   newstate=$(echo "$status"|awk -F' ' '{print $NF}')
   if [ "$newstate" = "UP" ]; then
       ifup "$name"
   elif [ "$newstate" = "DOWN" ]; then
       ifdown "$name"
   fi
done

該腳本在嘗試更改網路介面狀態之前不會檢查它,但這應該不是問題。

要使用它,只需將其放入/opt/bin/linkmonitor.sh,使其可執行並在末尾chmod +x /opt/bin/linkmonitor.sh添加一個 & 符號:/etc/rc.local

/opt/bin/linkmonitor.sh &

如果您需要更強大的解決方案,您可能會對路由故障轉移解決方案感興趣。

引用自:https://unix.stackexchange.com/questions/164837