How to ensure SMB based volume paths are available

smbterminal

My machine is mymac and the remote machine is remotemac(both are running El Capitan 10.11.6) – I reference a share on remotemac, located at //remotemac/path/to/remoteshare, as /Volumes/remoteshare.

Sometimes, especially when I have recently connected to that remote machine or share from Finder, the /Volumes/remoteshare path is available. But after some time, that /Volumes/remoteshare path is not available.

$ ls /Volumes
Macintosh HD
$ # connect to remoteshare from Finder
$ ls /Volumes
$ Macintosh HD    remoteshare
# After some time (a few hours)...
$ ls /Volumes
Macintosh HD 
$ # note that /Volumes/remoteshare is now missing

What can I do in my bash script to ensure that the remoteshare volume is present, or created before it is referenced?

Best Answer

In a script you can use the following basic construct:

#!bin/bash

if mount | grep -q "remoteshare"; then # check if remoteshare is available 
    exit
else
    echo not found
fi

grep -q ... suppresses normal output. If successful the script exits. In the other case it will echo "not found".

Instead of echo not found you can ssh into the remote server, run serveradmin and enable or restart the smb service – man serveradmin will show you how to do this. Then quit the ssh session and try to remount the SMB share.

To ssh passwordless into the server enable key based authentication - passing a password in a script is insecure and error prone. To use serveradmin on the remote server without sudoing, modify /etc/sudoers on the remote server and change the part:

## User privilege specification
##
root ALL=(ALL) ALL
%admin  ALL=(ALL) ALL

to

## User privilege specification
##
root ALL=(ALL) ALL
%admin  ALL=(ALL) ALL
your_remote_username ALL=(ALL) NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/serveradmin

Instead of the line echo not found use something like this then:

ssh username@remotemac
serveradmin stop smb
sleep 10
serveradmin start smb
sleep 2
exit
echo "SMB service was restarted"
mount_smbfs //your_remote_username:password@remotemac/folder /some/mntpoint

The inaccessibility of an SMB share may have many causes. It's probably impossible to cover all cases in one script.