if-up and if-down scripts with systemd

Posted by ads' corner on Monday, 2018-08-20
Posted in [Linux]

Everybody likes systemd, right? Well, not everybody. Who thought it might be a good idea to replace existing init systems with something which is big, monolithic, and not even feature complete?

A simple task: execute a script when an interface comes up, or goes down.

In the old days, on Debian or Ubuntu, one just added pre-up and post-down scripts in /etc/network/interfaces. But now, that file is gone, or empty. Ubuntu comes with netplan, which nobody else seems to use - luckily. NetworkManager is not used all the time, so one can’t depend on that either. And systemd does not have an option to do something simple like taking care of interfaces coming up and down. You can write yourself a target, but that only fires for the first time, not every time.

In the end, you have to listen to D-Bus messages. And suddenly the simple task of running a simple script turns into developing a full-featured daemon with D-Bus capabilities.

Someone else already took the stab, and developed networkd-dispatcher.

On Ubuntu, the package is called networkd-dispatcher, and usually is already installed. Unfurtunately it does not provide an option to place scripts or executables somewhere in /etc, so one has to use /usr/lib/networkd-dispatcher. There are 4 directories:

  • dormant.d
  • no-carrier.d
  • off.d
  • routable.d

Here I’m only interested in routable.d and off.d. Another minor problem is that each script is executed whenever any interface comes up or goes down. So the script must check the interface name as well. The name is provided in $IFACE. Example:


# must be /bin/bash, for some reasons /bin/sh does not work

if [ "$IFACE" == "eth0" ];
    # insert code here

Categories: [Linux]