Automatically mount CIFS share while connected to a particular network and then automatically unmount either just after or before disconnecting

Solution 1:

One possibility is a systemd automount.

[1] Create a mount point.

It cannot be under your home directory or /media. So for example create one at /mnt/SrvAshare.

[2] Then add - as an example - the following in /etc/fstab:

//serverA/sharename /mnt/SrvAshare cifs defaults,uid=1000,noauto,x-systemd.automount,x-systemd.idle-timeout=30,x-systemd.mount-timeout=10 0 0

[3] Then make systemd happy:

sudo systemctl daemon-reload
sudo systemctl restart remote-fs.target

It works by not mounting automatically on boot ( noauto ) but as required ( x-systemd.automount ) when you or some application or some process accesses the /mnt/SrvAshare mount point. It's failry seamless. If for example you just do an ls -l /mnt/SrvAshare it will mount the share.

x-systemd.idle-timeout=30 will unmount the share if it has not been used for 30 seconds ( user specified ).

x-systemd.mount-timeout=10 will try to mount the share for 10 seconds ( user specified ) then stop if unreachable. Useful if you inadvertently select the mount point when you are in the wrong location.