Hook a script into a network interface event on Linux
Have you ever wanted to run a script each time one of your network interface comes up ?
A pretty interesting situation might be that you are you don't trust your ISP (I mean, who does ?) so you want to enable your VPN each time you are at home, and you connect to your Wi-Fi or hook your Ethernet cable.
But for some reasons, at work you are not allowed to use a VPN, so ideally what you want to do is have a little script check whether you are at home and if yes enable your VPN otherwise disable it.
You can run the command below to create this base script and add in your own logic to do whatever you want whenever that specific interface is brought up
$ sudo nano /etc/network/if-up.d/<interface_name>
#!/usr/bin/env bash
[ "$IFACE" == $(basename $0) ] || exit 0
# your actual commands under here, so they run only when the current interface matches the filename
Then make the file executable with the following command
$ sudo chmod +x /etc/network/if-up.d/<interface_name>
You can turn down and up your interface with the commands below to test the hook
$ sudo ip link set <interface_name> down; sudo ip link set <interface_name> up
Just change if-up.d to other available directories to hook into a different event.
Thanks for your time.
Resources:
- https://manpages.debian.org/testing/ifupdown/interfaces.5.en.html [search for HOOK SCRIPTS]
- https://askubuntu.com/questions/406126/why-is-ifup-not-running-all-of-the-if-pre-up-d-scripts
- https://www.linuxquestions.org/questions/linux-networking-3/running-a-script-on-if-up-4175458108/
