Network Manager: Execute Script on Network Change
Execute a script when network changes is rather easy with systemd
(if you use the right services).
Network Manager
Assuming you are using NetworkManager
(default on Gnome):
systemctl enable NetworkManager-dispatcher systemctl start NetworkManager-dispatcher
The man page tells you to install a script in one of:
ls -la /etc/NetworkManager/dispatcher.d/ total 20 drwxr-xr-x 5 root root 4096 Feb 3 19:02 . drwxr-xr-x 7 root root 4096 Apr 20 18:43 .. drwxr-xr-x 2 root root 4096 Jul 13 2022 no-wait.d drwxr-xr-x 2 root root 4096 Jul 13 2022 pre-down.d drwxr-xr-x 2 root root 4096 Jul 19 16:21 pre-up.d
The script can use special variables with information about the connection parameters.
Example Script. The script monitor changes and execute commands
before connecting to a given Wifi. It has to be stored in
/etc/NetworkManager/dispatcher.d/pre-up.d/
#+begin_example bash #!/bin/sh
if [ “$2” = “pre-up” ]; then if [ “$CONNECTION_ID” = “MyWifi” ]; then
else
fi fi #+end_src
The documentation can also be found here.
Networkd
(Never tried myself)
The Arch documentation suggests to install and use
networkd-dispatcher
.
The reference can be found here, in the “Tips and tricks” section.