Search code examples
macosapplescriptdaemonnasafp

Script to detect if NAS is connected and if so mount Shares


I'm trying to find a way of mounting Shares (afp) on my NAS automatically. I use logins on it to control which shares are accessible by the computer (for privacy and other reasons). When switching logins not all of the shares get re-mounted which causes problems for some of the applications I run.

What I want to do is have a script which would run every time I login to the NAS (even if it's just guest login) then this script would mount the shares.

I was wondering if anyone could point me in the right direction. This is on an OS X computer so was thinking of using applescript to achieve this.

Thanks in advance

Tom


Solution

  • The basic idea would be to make a launchd agent to watch a folder for changes. You will want to watch the /Volumes folder because when you login to your NAS something will get mounted in the Volumes folder. Thus the watch agent will detect that something changed in the Volumes folder and it will run a script.

    It's very simple. You can google about launchd and find many examples. But to setup a watch folder use something like this...

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>WatchPaths</key>
        <array>
            <string>/Volumes</string>
        </array>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/bin/osascript</string>
            <string>/path/to/applescript</string>
        </array>
        <key>Label</key>
        <string>com.someName.plistFileName</string>
    </dict>
    </plist>
    

    So just create a text file with the above code. Save it with an extension of ".plist". Insert a path to the applescript in the ProgramArguments section and give it a name in the Label section.

    Put this plist in ~/Library/LaunchAgents folder and restart your computer. Now every time something changes in the /Volumes folder the applescript will be run.

    Then you just create the applescript properly. You will first need to check the Volumes folder and see if your NAS is mounted. If it is then mount any additional shares you want and if not then do nothing. You can google (or search stack overflow) how to mount shares using applescript.

    Good luck.