How to automatically run a command when the network is connected?

I wish to run a command automatically when I connect to wifi (or Ethernet). I have an older machine where I set up KDE to run the command on login. It waits for the network before running the command and works fine. But on my new machine, making KDE execute it on login fails because the command is run before the network is connected.

I suspect the old machine works, because it’s so slow that the wifi has a chance to connect before KDE gets around to running the startup command. Not because the command waits for the network.

I have tried making KDE autostart a bash script that waits a few seconds before running the command. That doesn’t work because KDE waits for the script first before it starts the wifi.

Search info on Network manager dispatcher. I guess this is likely all you need.

Hmm, it seems like what I need but I’m struggling to understand how to use it.

I created a dispatch script to run my command when the connectivity is “full.” I can see that the dispatcher service triggers when the wifi connects… but it still doesn’t run the command, and there are no errors.

You can probably write a systemd service to do this. Don’t ask me how, I suck at writing them

I just try my best to base my services off of what Tbg wrote in the old forums


Probably something with:

[Unit]
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/path/to/bash/or/bin

Note: That isn’t a full service that I typed, just part of it.

Let me give an example.
This is a script I use in order to have my NFS share mounted only when my laptop is connected to my home WiFi.

Script
#!/bin/bash

# Find the connection UUID with "nmcli con show" in terminal.
# All NetworkManager connection types are supported: wireless, VPN, wired...

if [[ "$CONNECTION_UUID" == "3df16735-4a9d-4ed1-be4f-45cdd064b810" ]] || [[ "$CONNECTION_UUID" == "154defea-79fa-41d4-b64a-51dbca09f791" ]]; then
    
    # Script parameter $1: NetworkManager connection name, not used
    # Script parameter $2: dispatched event
    
    case "$2" in
        "up")
            mount /media/asmt
            ;;
        "pre-down");&
        "vpn-pre-down")
            umount -l -f /media/asmt >/dev/null
            ;;
    esac
fi

An example of systemd unit generated with .desktop file:

MSM
# Automatically generated by systemd-xdg-autostart-generator

[Unit]

Documentation=man:systemd-xdg-autostart-generator(8)

SourcePath=/etc/xdg/autostart/msm_kde_notifier.desktop

PartOf=graphical-session.target

Description=MSM Notifier

After=graphical-session.target

[Service]

Type=exec

ExecStart=:/usr/bin/msm_kde_notifier

Restart=no

TimeoutSec=5s

Slice=app.slice