game, game. repeat.

How to Automatically Connect and Stay Connected to a Network Drive on OS X

Tue 13 September 2011 #Code

8

I keep my music and my photos on a server at home. Whenever I’m home I want all of my shares to be accessible automatically so I can launch iTunes and iPhoto without needing to do anything first (i.e. I don’t want to click anything to mount the drives before I start listening to Adagio for Tron). Here’s how I pulled it off.

The short version: I run a script that checks whether any mounts are missing and if possible it restores them. Here’s the script:

I run it once a minute using launchd for which there’s a good GUI; and here’s a tip in case you’re using RVM. If you want to try this at home, you’ll also need to install the gems ‘required’ at the top of the script. There are a number of other ways to achieve a similar effect, but I had trouble getting them to work:

  1. Mount a share at login. Judging by the number of discussions that reference this technique (and its cousins) it would seem popular, but it didn’t quite do what I wanted–each time my machine woke up from sleep or my wifi connection was interrupted, I’d lose my mounts and would need to manually remount them (or logout and login again).
  2. . This sure looked promising, but I found it to be unreliable in practice. Sometimes my mount would be there, sometimes it would not, sometimes it was there but no files appeared when I browsed…
  3. Detect when I connect to my home network, run a mounting script then (using SideKick). This solution got a bit closer–it reconnects my shares after I wake from sleep or my network connection was otherwise interrupted, but a loss of connection to my file server was not always proceeded by a loss of connection to the network, so there were plenty of times when I was still forced to manually connect to my drives.
  4. Use an app that does what my script does: detect when my file server is accessible and restore the connections to it as needed. BonjourMounter does just that, but I found it to be unreliable on Lion. A Lion compatible version is in the works, but after waiting a couple months, I decided to take matters into my own hands.

That’s all folks, thanks for stopping by!

**Updated on September 23, 2011: **

I’m finding Bonjour to be a bit flaky…there are plenty of times I can ping and mount my NAS, but it won’t show up in a Bonjour search. In light of that, I changed file_server_online() to use ping: