[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,

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,

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:

Related Post

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 *