[NetworkManager] Using dispatcher.d to run scripts based on network connectivity

This post is based on my personal need to mount/umount some network shares automatically when I’m switching between networks (e.g Homer/Office). Later on I was looking to make it more modular and came out with this solution, which can be further extended.

NetworkManager have a nice option to execute scripts after ones connect/disconnect to a network, you can find more in the Arch wiki page including some examples.

The problem I had with the way dispatcher.d works is that it execute all the files in the dispatcher.d folder in a linear order, and you have to code each script to handle the interface, connection state and the network you’re connecting to, so at first all my scripts looked something like this,

#!/bin/sh
### ONE OF OLD SCRIPT FORMAT

USER='username'
REMOTE='user@host:/remote/path'
LOCAL='/local/path'

interface=$1 status=$2
if [ "$CONNECTION_UUID" = "uuid" ]; then
  case $status in
    up)
      export SSH_AUTH_SOCK=$(find /tmp -maxdepth 1 -type s -user "$USER" -name 'ssh')
      su "$USER" -c "sshfs $REMOTE $LOCAL"
      ;;
    down)
      fusermount -u "$LOCAL"
      ;;
  esac
fi

I hated that I had to replicate the if/case template for each script I was adding, so I came with a different approach. And in my current setup I added the following file to the dispatcher.d folder

NetworkManager pass 2 parameters to each script it runs under the dispatcher directory,

  • $1 == The Device name, e.g eth0/enp0s25, tun0
  • $2 == The Connection state, e.g up/down, vpn-up

And so if we have connected to the home network with, The “master” script will list all the files under ${CONNECTION_UUID}/up  and will execute them one-by-one.

And so my dispatcher folder structure look like this,

# tree /etc/NetworkManager/dispatcher.d 

/etc/NetworkManager/dispatcher.d 
├── 4237f1af-15bf-46f7-a3a1-9a37c0d075de/
│   ├── down/
│   │   └── 00-umount-freenas-media*
│   └── up/
│       ├── 00-mount-freenas-media*
│       ├── 70-wifi-wired-exclusive.sh*
│       └── 99-set-display*
├── fdd94fcd-c801-401c-9caa-ebb21e10bc9e/
│   ├── down/
│   └── up/
│       └── 99-set-display*
...
├── Home -> 4237f1af-15bf-46f7-a3a1-9a37c0d075de/
├── Office -> fdd94fcd-c801-401c-9caa-ebb21e10bc9e/
...
└── 88-MASTER-DISPATCHER*

Remarks

  • Make sure to uncheck the “Auto connect to this network” for each profile in NetworkManager.
  • You will need to create the folders hierarchy your self.
  • Make sure the files under the dispatcher folder are marked as executables.

Links:

You may also like...

1 Response

  1. Haim Roman says:

    Very nice!

Leave a Reply

Your email address will not be published. Required fields are marked *