NetworkManager’s dispatcher scripts let you run custom commands automatically when network events happen, such as connecting to Wi-Fi or starting a VPN. This guide shows you how to create and use them safely, avoiding common pitfalls like infinite loops or permission errors.
What You’ll Need
- A Linux system with NetworkManager installed (most desktop distributions include it).
- Root or sudo access to create scripts in
/etc/NetworkManager/dispatcher.d/. - Basic familiarity with shell scripting (bash, sh, or similar).
Step-by-Step
- Understand how dispatcher works. NetworkManager runs every executable file in
/etc/NetworkManager/dispatcher.d/in alphabetical order whenever a network event occurs. The script receives two arguments: the interface name (e.g.,eth0,wlan0) and the action (e.g.,up,down,vpn-up). - Create your script file. Use a text editor to create a new file in the dispatcher directory. For example:
sudo nano /etc/NetworkManager/dispatcher.d/99-my-script. The leading number controls execution order; lower numbers run first. - Set proper permissions. The script must be executable and owned by root. Run:
sudo chown root:root /etc/NetworkManager/dispatcher.d/99-my-scriptandsudo chmod 755 /etc/NetworkManager/dispatcher.d/99-my-script. If the file is not executable or not owned by root, NetworkManager will ignore it. - Write a safe script. Start with a shebang line (
#!/bin/bash) and check the action before doing anything. For example:#!/bin/bash if [ "$2" = "up" ]; then # Your commands here logger "Network up on $1" fiAlways use
exit 0at the end to indicate success. - Avoid long-running tasks. Dispatcher scripts should finish quickly. If you need to start a process that runs in the background (like a sync tool), use
nohup ... &orsystemd-runto detach it. Otherwise, NetworkManager may hang or time out. - Prevent infinite loops. If your script triggers a network change (e.g.,
nmcli connection up), it can cause the dispatcher to run again, leading to a loop. Guard against this by checking a flag file or using a condition that prevents re-entry. - Test your script manually. Run it with sample arguments to see if it works:
sudo /etc/NetworkManager/dispatcher.d/99-my-script eth0 up. Check for errors in the output or injournalctl -u NetworkManager. - Enable and test with a real event. Restart NetworkManager (
sudo systemctl restart NetworkManager) or simply disconnect and reconnect your network to trigger the script. Verify that your commands executed as expected.
Common Mistakes
- Forgetting to make the script executable. This is the most frequent issue; NetworkManager silently skips non-executable files.
- Using relative paths. The script runs with a minimal environment, so always use absolute paths (e.g.,
/usr/bin/fooinstead offoo). - Assuming the action is always ‘up’ or ‘down’. There are many actions like
vpn-up,dhcp4-change,connectivity-change. Handle only what you need and ignore the rest. - Writing to stdout/stderr. Output from dispatcher scripts is not shown in a terminal; use
loggeror write to a file if you need logs. - Not considering environment variables. The script runs with a minimal PATH. Set
PATHat the top if you rely on commands outside the default.
Tips
- Use a separate script for each task. This makes debugging easier and avoids one broken script blocking others.
- Add a timeout. If you run external commands that might hang, use
timeout 10 /path/to/commandto limit execution time. - Log everything. Use
loggerto send messages to syslog; this helps when troubleshooting later. - Check NetworkManager’s documentation. The man page
man NetworkManager.dispatcherlists all possible actions and provides additional examples. - Use
nmclito get connection details. Inside a script, you can query the active connection withnmcli -t -f NAME connection show --activeto get the connection name.
Troubleshooting
If your script does not run, follow these steps:
- Check permissions: Run
ls -l /etc/NetworkManager/dispatcher.d/99-my-scriptand ensure it shows-rwxr-xr-xand ownerroot. - Check the action: Temporarily add
logger "Action: $2"at the top of the script to see what actions are being triggered. Then checkjournalctl -t NetworkManagerortail -f /var/log/syslog. - Test manually with the exact arguments: Run
sudo /etc/NetworkManager/dispatcher.d/99-my-script eth0 up(replaceeth0with your interface) and see if any errors appear. - Check for syntax errors: Run
bash -n /etc/NetworkManager/dispatcher.d/99-my-scriptto validate the script’s syntax. - Look at NetworkManager logs:
journalctl -u NetworkManager | grep -i dispatchermay show errors like “script not executable” or “failed to execute”. - If the script runs but commands fail: Add
set -xat the top to trace execution, and log the output to a file:exec > /tmp/dispatcher.log 2>&1.
Frequently Asked Questions
Can I use dispatcher scripts to run GUI applications?
Yes, but you must set the DISPLAY environment variable and ensure the user owns the process. For example: DISPLAY=:0 sudo -u username /path/to/app. However, it’s often better to use a user-level systemd service triggered by the dispatcher.
What is the difference between ‘up’ and ‘vpn-up’ actions?
‘up’ fires when any network interface comes up (Ethernet, Wi-Fi, etc.). ‘vpn-up’ fires specifically when a VPN connection is established. You can use both in the same script to handle different scenarios.
How do I run a script only for a specific Wi-Fi network?
Use nmcli -t -f active,ssid dev wifi inside the script to get the current SSID, then compare it to your target. For example: if nmcli -t -f active,ssid dev wifi | grep -q "^yes:MyNetwork"; then ...
Can I use dispatcher scripts to set environment variables for my user session?
No, dispatcher scripts run as root and do not affect existing user sessions. For user environment changes, use a user-level systemd service or a desktop autostart script that checks network status.
What happens if my script hangs?
NetworkManager may wait for the script to finish, delaying network operations. To avoid this, always keep scripts short and use timeout for any potentially long-running commands. You can also run the script in the background with & after detaching it from the terminal.
Is it safe to use dispatcher scripts to start a VPN automatically?
Yes, but be cautious. If the VPN fails, you might end up with no network. It’s recommended to add a fallback check: if the VPN does not connect within a few seconds, bring down the interface or notify the user.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Turn Off Backup Encryption in iTunes?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It