Sometimes it is required that you can react on state changes of your network interfaces. Maybe you want to get notified by mail or you want to execute a script that does something in case an event is trapped. As usual I will be using CentOS 7 for this little demonstration but as most distributions use systemd and NetworkManager nowadays this should work more or less the same on Debian based distributions.
As this will be a short post anyway: The way to do it is to use the dispatcher scripts coming with Network Manager. All you need to do for getting notified on down or up events is to create a script in /etc/NetworkManager/dispatcher.d/:
[email protected]:/etc/NetworkManager/dispatcher.d/  pwd /etc/NetworkManager/dispatcher.d [email protected]:/etc/NetworkManager/dispatcher.d/  cat 30-network #!/bin/bash INTERFACE=$1 ACTION=$2 echo $INTERFACE >> /var/log/tmp.log echo $ACTION >> /var/log/tmp.log
The script will get two parameters passed in by default: The name of the interface and the action that just happened. What you do with these is totally up to you. The only point you need to take care of (which is also mentioned in the documentation): “Each script should be a regular executable file, owned by root. Furthermore, it must not be writable by group or other, and not setuid.”
[email protected]:/etc/NetworkManager/dispatcher.d/  ls -la total 16 drwxr-xr-x. 5 root root 131 Aug 6 17:02 . drwxr-xr-x. 7 root root 134 Jul 20 10:18 .. -rwxr-xr-x. 1 root root 175 Jan 2 2018 00-netreport -rwxr-xr-x. 1 root root 1123 May 15 15:03 11-dhclient -rwxr-xr-x. 1 root root 985 Sep 15 2017 20-chrony -rwxr-xr-x. 1 root root 108 Aug 6 17:02 30-network drwxr-xr-x. 2 root root 6 Jun 27 16:39 no-wait.d drwxr-xr-x. 2 root root 6 Jun 27 16:39 pre-down.d drwxr-xr-x. 2 root root 6 Jun 27 16:39 pre-up.d
As soon as you have your script in place it will get kicked off when the interface state is changing:
[email protected]:/etc/NetworkManager/dispatcher.d/  systemctl restart network [email protected]:/etc/NetworkManager/dispatcher.d/  cat /var/log/tmp.log connectivity-change enp0s3 down enp0s8 down enp0s3 up connectivity-change enp0s8 up
Hope that helps …