Ubuntu – Network Manager script when interface up

network-manager

Because I am using Bionic Beaver/Ubuntu 18.04, the network settings in /etc/network/interfaces are being ignored and the settings in /etc/NetworkManager/system-connections/'eth0' are being used for i) static ip ii) gateway etc.

I wish to restart the sshd service every time the interface comes up. It doesn't work in the normal place /etc/network/interfaces since I'm using Gnome. Where can I place a NetworkManager script to be run every time a specific interface comes up?

Best Answer

  • The solution is to create dispatchers scripts in /etc/NetworkManager/dispatcher.d. For example, you could log events in journald by placing the following script at /etc/NetworkManager/dispatcher.d/log-iface-events.sh:

    #!/usr/bin/env bash
    
    interface=$1
    event=$2
    
    echo "$interface received $event" | systemd-cat -p info -t dispatch_script
    

    Remember to give it execution permissions:

    chmod +x /etc/NetworkManager/dispatcher.d/log-iface-events.sh
    

    The bad news is that scripts are no longer tied to a given interface or events such as up or down. Hence, you must check all of that in your script. If you want this script to run only for eth0, you must filter that by hand putting something like the following in your script:

    [[ $interface == "eth0" ]] || return 0
    

    For example:

    #!/usr/bin/env bash
    
    interface=$1
    event=$2
    
    if [[ $interface != "eth0" ]] || [[ $event != "up" ]]
    then
      return 0
    fi
    
    # place your commands bellow this line
    

    Will run only if it is dealing with up events for eth0 interface.

    You can have many scripts. According to man 8 networkmanager, scripts will run in alphabetical order. This seems to include the scripts in subdirectories. You MUST read this manpage.