Okay, causing a systemd service to trigger when the Wi-Fi network changes primarily depends on what network management tool you're using. The most common ones are NetworkManager and systemd-networkd.
Here's how you can do it with each:
Method 1: Using NetworkManager Dispatcher Scripts (Most Common for Desktops/Laptops)
NetworkManager runs scripts in /etc/NetworkManager/dispatcher.d/ in response to network events. You can use a dispatcher script to start your systemd service.
-
Create your systemd service unit file:
Let's say your service is /etc/systemd/system/my-wifi-triggered-service.service. This service will contain the actual commands you want to run.
[Unit]
Description=My Wi-Fi Triggered Action
# Add After=network-online.target if your script needs network,
# but the dispatcher itself runs after the network event.
[Service]
Type=oneshot
ExecStart=/usr/local/bin/my-wifi-action-script.sh
# You might want to pass information from the dispatcher script
# via environment variables or arguments if needed.
# For example, if your script needs to know the interface or SSID:
# ExecStart=/usr/local/bin/my-wifi-action-script.sh %E{NM_DISPATCHER_ACTION} %E{CONNECTION_ID} %E{DEVICE_IFACE}
[Install]
# This service is started on demand by the dispatcher, so no WantedBy typically needed.
Type=oneshot: Assumes your script performs a task and exits.
/usr/local/bin/my-wifi-action-script.sh: This is the script that does the actual work.
-
Create the action script (/usr/local/bin/my-wifi-action-script.sh):
This script will be executed by your systemd service.
#!/bin/bash
# /usr/local/bin/my-wifi-action-script.sh
# Example: Log information about the event
# The dispatcher script can pass these as arguments or environment variables
# to the systemd service, which then passes them here.
# For simplicity, let's just log a generic message.
logger "My Wi-Fi action script was triggered by systemd!"
echo "Wi-Fi triggered action executed at $(date)" >> /tmp/wifi_action.log
# If your systemd service passed arguments:
# DISPATCHER_ACTION="$1"
# CONNECTION_ID="$2"
# DEVICE_IFACE="$3"
# logger "Wi-Fi action for: Action=$DISPATCHER_ACTION, Connection=$CONNECTION_ID, Interface=$DEVICE_IFACE"
# Add your actual commands here
# e.g., restart a VPN, sync files, send a notification
exit 0
Make it executable: sudo chmod +x /usr/local/bin/my-wifi-action-script.sh
-
Create a NetworkManager dispatcher script:
Create a script in /etc/NetworkManager/dispatcher.d/. The name should typically start with a number to control ordering if you have multiple scripts, e.g., 90-my-wifi-trigger.
#!/bin/bash
# /etc/NetworkManager/dispatcher.d/90-my-wifi-trigger
# Arguments passed by NetworkManager:
# $1: Interface name (e.g., wlan0)
# $2: Action (e.g., "up", "down", "connectivity-change", "hostname")
# Environment variables available (among others):
# CONNECTION_ID: Name of the connection profile (often the SSID)
# CONNECTION_UUID: UUID of the connection profile
# DEVICE_IFACE: Interface name (same as $1)
# IP4_ADDRESS_0: First IPv4 address (e.g., 192.168.1.10/24)
# IP6_ADDRESS_0: First IPv6 address
# CONNECTIVITY_STATE: (for connectivity-change action) e.g. FULL, LIMITED, NONE
# We only care about Wi-Fi interfaces and specific events
# Check if DEVICE_TYPE is wifi (more reliable than interface name patterns)
if [ "$DEVICE_TYPE" != "wifi" ]; then
exit 0
fi
# Define what constitutes a "change" for you
# Example 1: Trigger on any 'up', 'down', or 'connectivity-change' for a Wi-Fi interface
case "$2" in
up|down|connectivity-change)
logger "NM Dispatcher: Wi-Fi event on $1 ($CONNECTION_ID). Action: $2. Triggering systemd service."
# You can pass information to the service if you modify its ExecStart
# For example:
# systemctl set-environment NM_DISPATCHER_ACTION="$2"
# systemctl set-environment CONNECTION_ID="$CONNECTION_ID"
# systemctl set-environment DEVICE_IFACE="$1"
systemctl start my-wifi-triggered-service.service
;;
*)
# Other actions we don't care about
;;
esac
exit 0
-
Make the dispatcher script executable:
sudo chmod +x /etc/NetworkManager/dispatcher.d/90-my-wifi-trigger
-
Reload systemd manager configuration (if you created/changed the service file):
sudo systemctl daemon-reload
Now, whenever NetworkManager brings a Wi-Fi interface up, down, or its connectivity-changes, the dispatcher script will run. If it's a Wi-Fi interface, it will start your my-wifi-triggered-service.service.
To detect a specific SSID change:
Your dispatcher script would need to store the previously connected SSID and compare it.
#!/bin/bash
# /etc/NetworkManager/dispatcher.d/90-my-wifi-ssid-change-trigger
PREVIOUS_SSID_FILE="/run/NetworkManager/previous_wifi_ssid" # Use /run for temp files
if [ "$DEVICE_TYPE" != "wifi" ]; then
exit 0
fi
current_ssid="$CONNECTION_ID" # CONNECTION_ID is usually the SSID
# Handle "up" or "connectivity-change" (when fully connected)
if [[ "$2" == "up" || ("$2" == "connectivity-change" && "$CONNECTIVITY_STATE" == "FULL") ]]; then
previous_ssid=""
if [ -f "$PREVIOUS_SSID_FILE" ]; then
previous_ssid=$(cat "$PREVIOUS_SSID_FILE")
fi
if [ "$current_ssid" != "$previous_ssid" ]; then
logger "NM Dispatcher: Wi-Fi SSID changed or connected. New: '$current_ssid', Previous: '$previous_ssid'. Triggering service."
systemctl start my-wifi-triggered-service.service
echo "$current_ssid" > "$PREVIOUS_SSID_FILE"
fi
elif [ "$2" == "down" ]; then
logger "NM Dispatcher: Wi-Fi $1 disconnected. Triggering service."
# Potentially trigger service on disconnect as well
systemctl start my-wifi-triggered-service.service
# Clear the previous SSID or set a special value like "DISCONNECTED"
echo "DISCONNECTED" > "$PREVIOUS_SSID_FILE"
fi
exit 0
Remember to sudo chmod +x this script.
Method 2: Using systemd-networkd-dispatcher (If you use systemd-networkd)
If your system uses systemd-networkd for network configuration (common on servers, or if you've configured it specifically), you'd use networkd-dispatcher.
-
Install networkd-dispatcher if not present:
The package name might vary (e.g., networkd-dispatcher on Debian/Ubuntu, systemd-networkd-wait-online might be part of it, or a separate package).
sudo apt install networkd-dispatcher or sudo dnf install networkd-dispatcher
-
Create your systemd service unit file (my-wifi-triggered-service.service) and the action script (/usr/local/bin/my-wifi-action-script.sh) as described in Method 1.
-
Create a dispatcher script for networkd-dispatcher:
Scripts are placed in subdirectories of /etc/networkd-dispatcher/ corresponding to the state. For example, to react when an interface becomes "routable" (has an IP and routes):
Create /etc/networkd-dispatcher/routable.d/50-my-wifi-trigger
#!/bin/bash
# /etc/networkd-dispatcher/routable.d/50-my-wifi-trigger
# Arguments passed:
# $1: Interface name (e.g., wlan0)
# $2: Operational state (e.g., "routable", "off", "no-carrier", "carrier", "degraded")
# For scripts in routable.d, $2 is typically "routable"
# For scripts in configured.d, $2 is typically "configured"
# For scripts in carrier.d, $2 is typically "carrier"
# For scripts in degraded.d, $2 is typically "degraded"
# For scripts in off.d, $2 is typically "off"
# We need to identify if it's a Wi-Fi interface.
# This is trickier with just systemd-networkd as it's lower level.
# You might check if the interface name starts with "wlan" or "wlp".
if [[ "$1" != wlan* && "$1" != wlp* ]]; then
exit 0
fi
logger "networkd-dispatcher: Wi-Fi event on $1 state $2. Triggering systemd service."
systemctl start my-wifi-triggered-service.service
# To get SSID with systemd-networkd, you might need to use `iwgetid -r "$1"`
# if iwgetid is available and the interface is up.
# current_ssid=$(iwgetid -r "$1")
# logger "networkd-dispatcher: Current SSID on $1 is $current_ssid"
exit 0
Make it executable: sudo chmod +x /etc/networkd-dispatcher/routable.d/50-my-wifi-trigger
You might also want scripts in off.d or no-carrier.d to detect disconnections.
Detecting specific SSID change with systemd-networkd-dispatcher:
This is harder as systemd-networkd is less aware of SSIDs directly. You'd use iwgetid within the script and manage state similar to the NetworkManager example (e.g., in /run/networkd-dispatcher/previous_wifi_ssid).
Which Method to Choose?
- Use NetworkManager (Method 1) if your system uses NetworkManager. This is the default for most desktop Linux distributions (Ubuntu, Fedora, etc.).
nmcli command will work.
- Use
systemd-networkd-dispatcher (Method 2) if your system is configured to use systemd-networkd. networkctl command will show interface status.
Important Considerations:
- Permissions: Dispatcher scripts run as root, so be careful with the commands they execute.
- Idempotency: If your
my-wifi-action-script.sh is long-running or should only run once even if triggered multiple times quickly, you'll need to build idempotency into it (e.g., using a lock file).
- Logging: Use
logger or redirect output to a log file from your scripts for debugging.
- Environment: The environment in which dispatcher scripts run is minimal. If your actual action script relies on user-specific environment variables, they won't be available.
- Alternative for fine-grained D-Bus monitoring: For very specific events or if you want to avoid dispatcher scripts, you could write a custom script/daemon that listens to D-Bus signals from NetworkManager (e.g.,
org.freedesktop.NetworkManager.Device.StateChanged or org.freedesktop.NetworkManager.ActiveConnection.StateChanged) and then starts your systemd service. This is more complex.
Choose the method that aligns with your system's network management setup. For most users, NetworkManager is the way to go.