Wifi

使用 NetworkManager 在連接到乙太網時禁用 Wifi

  • July 7, 2020

當我通過乙太網(有線)連接到網路時,如何禁用我的 Wifi 無線電,但如果我沒有有線連接,則啟用 Wifi 連接?本質上,我想要我的有線/無線連接狀態的 XOR 開關。

我找到了一個由 Ilija Matoski 編寫的腳本來完成這個任務,它屬於/etc/NetworkManager/dispatcher.d/70-wifi-wired-exclusive.sh.

#!/bin/sh

name_tag="wifi-wired-exclusive"
syslog_tag="$name_tag"
skip_filename="/etc/NetworkManager/.$name_tag"

if [ -f "$skip_filename" ]; then
   exit 0
fi

interface="$1"
iface_mode="$2"
iface_type=$(nmcli dev | grep "$interface" | tr -s ' ' | cut -d' ' -f2)
iface_state=$(nmcli dev | grep "$interface" | tr -s ' ' | cut -d' ' -f3)

logger -i -t "$syslog_tag" "Interface: $interface = $iface_state ($iface_type) is $iface_mode"

enable_wifi() {
   logger -i -t "$syslog_tag" "Interface $interface ($iface_type) is down, enabling wifi ..."
   nmcli radio wifi on
}

disable_wifi() {
   logger -i -t "$syslog_tag" "Disabling wifi, ethernet connection detected."
   nmcli radio wifi off
}

if [ "$iface_type" = "ethernet" ] && [ "$iface_mode" = "down" ]; then
   enable_wifi
elif [ "$iface_type" = "ethernet" ] && [ "$iface_mode" = "up"  ] && [ "$iface_state" = "connected" ]; then
   disable_wifi
fi

此外,要禁用此切換操作,您可以創建文件/etc/NetworkManager/.wifi-wired-exclusive(例如 via touch)。

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