Ubuntu: NetworkManager Scripts

I have found that there are times when I would like to have certain services stopped and restarted when I bring network interfaces down and up.  I looked around to see if there was a place to dump some scripts, in hopes that NetworkManager would automatically run these.  There is.  For this example, I will use my firewall script, as I need to have it restarted when I bring my laptop home from work, or switch VLANs, or enabled WiFi...etc.
 

1.) Switch into the /etc/NetworkManager/dispatcher.d directory, as this is where all these scripts will live:

cd /etc/NetworkManager/dispatcher.d

2.) Next, you'll need to know the order in which these scripts get executed....it's alphabetical (or numerical depending on how you look at it).  Safe bet, is to call the scripts number_description. This will make the execution order a little easier to see.  For my firewall script, I wanted it to be executed last so I called it 99_firewall:

sudo vi 99_firewall

3.) The scripts use a case of up or down to determine when/what to run.  So, I created my script (very simple) like so:

#!/bin/sh  
 
case "$2" in
    up)  
    /etc/init.d/firewall restart  
        ;;  
    esac

4.) Finally, just make this script executable:

sudo chmod +x 99_firewall

 

You should be able to test this out by simply stopping your firewall script (or whatever).  And then simply disconnecting and reconnecting your interface.  You should then check and see if you firewall automatically restarted.  Mine did 8)