Automatically disable wifi (wireless) when wired?
Solution 1:
The following script, put in /etc/NetworkManager/dispatcher.d/99-disable-wireless-when-wired
, mostly works—it disables wireless even when I want to share wired with wireless or vice-versa.
To do this, run the following command in terminal:
sudo nano /etc/NetworkManager/dispatcher.d/99-disable-wireless-when-wired
And paste the following code into the text editor.
#!/bin/sh
myname=${0##*/}
log() { logger -p user.info -t "${myname}[$$]" "$*"; }
IFACE=$1
ACTION=$2
release=$(lsb_release -s -c)
case ${release} in
trusty|utopic) nmobj=nm;;
*) nmobj=radio;;
esac
case ${IFACE} in
eth*|usb*|en*)
case ${ACTION} in
up)
log "disabling wifi radio"
nmcli "${nmobj}" wifi off
;;
down)
log "enabling wifi radio"
nmcli "${nmobj}" wifi on
;;
esac
;;
esac
Then save and exit.
Note the following conditions on the script, as documented in the NetworkManager manual page:
Each script should be:
- a regular file,
- owned by root,
- not writable by group or other,
- not set-uid,
- and executable by the owner.
Instead of nmcli radio wifi off
(or nmcli nm wifi off
for older
versions of NetworkManager), there is also rfkill block wifi
.
However, if rfkill
is used instead of nmcli
, newer versions of
NetworkManager will turn wifi back on during boot.
Solution 2:
Based on the other answer, I came up with this (tested on Kubuntu 20.04).
It auto-disconnects wifi on wired connection, except for connection names ending with -hotspot
(like the default names Kubuntu uses for created access point connections). It allows sharing wireless hotspot from cable. So, instead of disabling radio for all WiFi, it just disconnects the network you're using. When the cable is unplugged, it reconnects the wireless device wlo1
, which makes it reconnect the last used WiFi network.
Note that if you turn off the computer without cable and plug it before turning it on, it may start with both wifi and wired connections. Similarly, I presume, if you remove the cable while computer is off, it won't auto-connect at startup, I think.
sudo nano /etc/NetworkManager/dispatcher.d/99-disable-wireless-when-wired
sudo chmod 0744 /etc/NetworkManager/dispatcher.d/99-disable-wireless-when-wired
#!/bin/sh
myname=${0##*/}
log() { logger -p user.info -t "${myname}[$$]" "$*"; }
IFACE=$1
ACTION=$2
case ${IFACE} in
eth*|usb*|en*)
case ${ACTION} in
up) # when plugging ethernet cable
log "disconnecting wifi when wired"
# list active connections
nmcli -f uuid,type,name connection show --active |
# filter wifi except names ending with -hotspot, return UUID
awk '/\S\s+wifi\y/ && !/-hotspot\s*$/ {print $1;}' |
# disconnect these UUIDs
xargs -r nmcli connection down
;;
down) # when unplugging ethernet cable
log "reconnecting wifi when not wired"
# auto-choose wifi to reconnect
nmcli device connect wlo1
;;
esac
;;
esac