Okay, triggering a systemd service specifically when your Wi-Fi network changes (connecting to a new one, reconnecting to an old one after losing signal, or potentially disconnecting) is a common requirement.
The most standard and robust way to achieve this is by using the NetworkManager dispatcher scripts. NetworkManager is the most common network management service on many Linux distributions, and it's designed to run scripts in a specific directory whenever network connection states change.
NetworkManager executes scripts located in /etc/NetworkManager/dispatcher.d/ whenever a connection is brought up or down. These scripts are run with root privileges and receive arguments indicating the interface name and the action.
Create your Systemd Service:
If you don't already have a service file for the task you want to perform, create one. Let's call it my-wifi-change-service.service and place it in /etc/systemd/system/:
ini
# /etc/systemd/system/my-wifi-change-service.service
[Unit]
Description=My Service to Run on Wi-Fi Network Change
# Optional: Ensure network is available before trying (though the dispatcher handles this)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot # Or simple, or notify depending on your service
ExecStart=/usr/local/bin/my-wifi-action-script # Or the command to run your task
# User=youruser # If you need it to run as a specific user
[Install]
# This service isn't typically enabled to start at boot like this,
# it's triggered by the dispatcher script.
# But if your action script is just a simple command, Type=oneshot
# is fine, and you'll start/stop it from the dispatcher.
Replace /usr/local/bin/my-wifi-action-script with the actual command or script you want to run.
Adjust Type= based on how your service behaves. oneshot is good for a script that runs and exits.
Run sudo systemctl daemon-reload after creating or modifying the service file.
Create the NetworkManager Dispatcher Script:
Create a script in /etc/NetworkManager/dispatcher.d/. Give it a name that suggests its purpose, like 99-trigger-my-service.sh. The 99- prefix helps ensure it runs late.
bash
#!/bin/bash
# Arguments passed by NetworkManager:
# $1: Interface name (e.g., wlan0, eth0)
# $2: Action (e.g., up, down, pre-up, pre-down, vpn-up, vpn-down, hostname, dhcp4-change, dhcp6-change)
IFACE="$1"
ACTION="$2"
# --- Configuration ---
# Systemd service to trigger
SERVICE_NAME="my-wifi-change-service.service"
# Specify actions that should trigger the service
# 'up' means the connection has been successfully established and IP is assigned
TRIGGER_ACTIONS="up dhcp4-change"
# Only trigger for wireless interfaces (optional, but likely what you want)
# You can check the interface type, or just filter by common Wi-Fi names
# For a more robust check, you could use `iwconfig "$IFACE"` or `ip link show "$IFACE"`
WIFI_IFACES="wlan* wlp*" # Adjust if your Wi-Fi interfaces have different names
# --- Logic ---
# Check if the interface name matches a Wi-Fi interface pattern
IS_WIFI=false
for pattern in $WIFI_IFACES; do
if [[ "$IFACE" == $pattern ]]; then
IS_WIFI=true
break
fi
done
if ! $IS_WIFI; then
# Not a Wi-Fi interface, exit
exit 0
fi
# Check if the action is one that should trigger the service
SHOULD_TRIGGER=false
for trigger_action in $TRIGGER_ACTIONS; do
if [[ "$ACTION" == "$trigger_action" ]]; then
SHOULD_TRIGGER=true
break
fi
done
if $SHOULD_TRIGGER; then
echo "NetworkManager event: Wi-Fi interface $IFACE is $ACTION. Triggering service $SERVICE_NAME." | systemd-cat -p info -t NetworkManager-dispatcher
# Use systemctl to start the service.
# --no-block prevents the script from waiting for the service to finish
# and lets NetworkManager continue its work.
# --user if it's a user service, otherwise it's a system service (default)
sudo systemctl start "$SERVICE_NAME" --no-block
# If your service is Type=oneshot, you might want restart instead of start
# sudo systemctl restart "$SERVICE_NAME" --no-block
elif [[ "$ACTION" == "down" ]]; then
echo "NetworkManager event: Wi-Fi interface $IFACE is $ACTION." | systemd-cat -p info -t NetworkManager-dispatcher
# Optional: Stop the service when Wi-Fi goes down
# sudo systemctl stop "$SERVICE_NAME" --no-block
else
# Log other Wi-Fi actions if needed for debugging
# echo "NetworkManager event: Wi-Fi interface $IFACE is $ACTION (ignored)." | systemd-cat -p debug -t NetworkManager-dispatcher
exit 0 # Do nothing for other actions
fi
exit 0
Connect to a Wi-Fi network. Check the logs (journalctl -f) for messages tagged with NetworkManager-dispatcher and see if your service starts.
Switch to a different Wi-Fi network. Observe logs and service status again.
Disconnect from Wi-Fi.
Explanation:
The dispatcher script 99-trigger-my-service.sh is executed by NetworkManager.
It receives the interface name ($1) and action ($2).
It first checks if the interface is likely a Wi-Fi interface (based on common naming patterns).
It then checks if the action is one of the specified trigger actions (up, dhcp4-change). The up action signifies a successful connection and IP address assignment (via DHCP usually). dhcp4-change might also be useful if the IP address changes while connected.
If both conditions are met, it uses sudo systemctl start my-wifi-change-service.service --no-block to tell systemd to start your target service.
--no-block is important so the script doesn't hang while your service runs.
Considerations for the Dispatcher Method:
Permissions: Dispatcher scripts run as root. If your task needs to run as a specific user, you'll need to handle that in your service file (User=) or within the script (using sudo -u youruser ...). Running a user service (--user) from a root dispatcher script requires careful configuration (often involving loginctl enable-linger). Running a system service (Type=oneshot) that executes your user's script is often easier.
Idempotency: Your my-wifi-action-script should ideally be idempotent, meaning running it multiple times won't cause issues. This is because NetworkManager might trigger the 'up' action again under certain circumstances (e.g., DHCP lease renewal).
Logging: Use systemd-cat in the dispatcher script to log messages to the systemd journal, making debugging easier.
Specific Network: If you need to trigger only for a specific Wi-Fi network (by SSID), the dispatcher script will need to query NetworkManager's D-Bus interface or parse the output of nmcli device status or nmcli connection show --active. This adds complexity. The script provided triggers for any Wi-Fi connection coming up.
Method 2: Using systemd-networkd Dispatcher (if not using NetworkManager)
If you are using systemd-networkd instead of NetworkManager, it has a similar mechanism with networkd-dispatcher.
Ensure networkd-dispatcher is installed and enabled.
Create your Systemd Service (same as step 1 above).
Create the networkd-dispatcher Script: These go in /etc/systemd/network/dispatcher.d/ or similar paths. The scripts receive interface name and state change as arguments (similar to NM).
bash
#!/bin/bash
# Arguments passed by networkd-dispatcher:
# $1: State (e.g., routable, degraded, no-carrier, off, etc.)
# $2: Interface name (e.g., wlan0, eth0)
STATE="$1"
IFACE="$2"
SERVICE_NAME="my-wifi-change-service.service"
# Check if it's a Wi-Fi interface and the state indicates it's ready
# 'routable' means IP addresses are assigned and routes are configured
if [[ "$IFACE" == wlan* || "$IFACE" == wlp* ]] && [[ "$STATE" == "routable" ]]; then
echo "networkd-dispatcher event: Wi-Fi interface $IFACE is $STATE. Triggering service $SERVICE_NAME." | systemd-cat -p info -t networkd-dispatcher
sudo systemctl start "$SERVICE_NAME" --no-block
fi
exit 0
Make the Script Executable:sudo chmod +x /etc/systemd/network/dispatcher.d/your-script-name.sh
Test: Restart systemd-networkd and networkd-dispatcher. Connect/switch Wi-Fi networks.
Method 3: Monitoring D-Bus (More Complex)
You could write a long-running systemd service that uses a D-Bus library (in Python, C, etc.) to listen for signals from NetworkManager (org.freedesktop.NetworkManager) or systemd-networkd (org.freedesktop.network1) related to state changes or active connections. When a relevant signal is received (e.g., StateChanged, ActiveConnectionChanged), the listener service could then trigger your target service (systemctl start my-wifi-change-service.service).
This method is more flexible and potentially more precise if you need to react to very specific nuances of state change not covered by the dispatcher actions, but it requires writing and maintaining a D-Bus client application.
Why network-online.target is NOT ideal for this specific case:
The network-online.target is designed to be reached once during boot when the network is generally considered usable. Adding After=network-online.target and Wants=network-online.target to your service file makes it start after the initial network setup is complete at boot. It will not automatically re-trigger if you later disconnect from one Wi-Fi network and connect to a different one while the system is running. It's for initial network readiness, not ongoing network change events.
Conclusion:
For triggering a systemd service specifically on Wi-Fi network changes during a session, the NetworkManager dispatcher scripts (Method 1) are the most common, recommended, and easiest approach for systems using NetworkManager. If you use systemd-networkd, use its dispatcher mechanism (Method 2). Avoid polling or relying solely on network-online.target for this task.