Stop/start SYSTEMD service on specific SSID

I only connect to my NAS laptop (arch linux) drives via NFS on a specific 5G router with a specific SSID for example NASrouter_5G. When I change the wifi, that happens frequently, to another router for example NoNasRouter_2G I want the drives to be unmounted and remounted back when I connect to NASrouter_5G again since the file manager freeze if I don’t.

In my research I found a [Match] syntax but this only detects the interface name and that is always wifi0, so that doesn’t seem to work.
Also the networkd-dispatcher looks promising I just didn’t found anything on how to use it.

So my Question is:

How do I do that, preferably with systemd since I mount the drives on startup and after hybernation with systemd and it works fine. But any way is appreciated since I don’t want to type sudo systemctl stop nfs_mount or some alias every time I change the network.

The mounting service file contains the following:

[jack@jacks ~]$ cat /usr/lib/systemd/system/nfs_mount.service 
[Unit]
Descritpion=Documents Mount NAS systemctl start nfs_mount
After=suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target syslog.target network-online.target
Wants=syslog.target network-online.target

[Service]
Type=oneshot
ExecStart=/home/jack/nfs_mount.sh

[Install]
WantedBy=multi-user.target suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target
Asked By: Ingo Mi

||

There is systemd unit predefined conditions that can be used, but any of them match this use case.

Since your service is a oneshot one, the service will become inactive once the main process is termintaed. So using simple to daemonize the service with an infinite loop and wrapping your nfs_mount.sh script with an IF statement based on the SSID comparison can make it :

#!/bin/sh  
while :
do
    sleep 5
    if [ "$(iwgetid -r)" == 'your_ssid' ] ; then 
      # Your code here
    else 
      # If it was not a oneshot service you can make a place here for a code to kill the service
    fi
done

So in this way the filesystem is mounted only if your system is connected to a WIFI that matches the wanted SSID.

Answered By: Reda Salih
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.