Pragmatism in the real world

Automatically mounting a network drive on Mac

I have so many photos that I can’t store them all on my hard drive and keep them on my NAS. While on my home network, it would be convenient to automatically mount the NAS folder onto my Mac as I keep forgetting before I open Lightroom. Usually I would use automount to do this, but Lightroom cannot see automounted folders, so I decided to use a combination of AppleScript and Keyboard Maestro.

Mount a shared folder using AppleScript

There are two key tasks that the AppleScript has to perform:

  1. Mount the share if it’s not already mounted
  2. Only mount the share if the current WiFi network is one of my home ones

Let’s look at these in reverse order.

Mounting the share

To mount the share, we need this AppleScript:

tell application "System Events"
    if "photos" is not in the name of every disk then mount volume "afp://britannia.localdomain/photos"
end tell

AppleScript is one of the more verbose scripting languages but it’s fairly clear what’s going on. There’s a collection of current mount points what we access with the name of every disk construct which is part of System Events and check if the the share folder is not already mounted with if "photos" is not in the {list} construct (told you it was verbose!). Mounting is done with mount volume which takes a connection string.

Only mount if WiFi network is known

There are two network names for my home network, so we need to mount the photos share if we’re connected to either. This is done using this AppleScript:

set theListOfSSIDs to {"19FT", "19FT 5G"}
set mySSID to do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'"

if theListOfSSIDs contains mySSID then
  -- mount if we need to
end if

That’s possibly the weirdest path ever, but airport -I from the Apple80211 framework will tell us information about our currently connected network. A bit of awk and we have our current SSID. We can now compare that to the list of known SSIDs using if {list} contains {thing} and if this is the right network, we can go ahead and mount the network drive.

Running our script

Now that we have a script that will mount the drive, we need to run it when any of these events happen:

  • I log in
  • The computer wakes up
  • The computer connects to a different WiFi network

The easiest way to trigger an action on events like these is to use Keyboard Maestro, so I created a macro that looks like this:

I’m not sure how long the pause needs to be, but 3 seconds work on this old 2013 Mac and I don’t need it any faster.

All done

That’s it. Now, whenever I’m on my home WiFi, my NAS’s photos share is mounted and I never have to think about it!