Terminal (bash) – copy files from Windows (SMB) shares without mounting

bashmountscriptsmbterminal

In past OSX versions, one could copy files from SMB shares like so:

smbclient //my-server/foo -U USER%PASS -I 127.0.0.1 -c "get my.file" 

However, in recent versions, sbmclient has been replaced with smbutil which does not have copying capabilities. As far as I can tell, the only replacement is mount -t smbfs. I am not aware of any way to install smbclient on OSX (Print file from terminal via smb).

Mounting is pretty annoying though:

  1. You have to create a folder for the mount point (what if it already exists?)
  2. If the same folder has already been mounted on a different folder, mount will fail (with a pretty misleading error)
  3. There's no "structured" way to tell which shares are mounted where (that I know of), meaning you'll have to grep/sed the output of df to try and work around the issues above

Basically I just want to reliably copy a file from an SMB share in a bash script, and the issues above make it more complicated than it should be (and already was before smbclient was dropped).

Best Answer

You cannot do that without first mounting the share.

For mounting it from the command-line, whether through Terminal or from an SSH session, there are several methods with different advantages and disadvantages.

A few variables, to make it easier to copy/paste the rest :

user=my_username; pass=my_password; server=my_server; share=my_share

Method 1

Create a temporary folder, mount into that, then unmount and remove the temporary folder.

This is the only method that also works without a user being logged in, like through a SSH session opened right after boot. But if a user is actually logged in there is still an icon on the desktop to access the share through the Finder.

dir=$(mktemp -d)
mount -t smbfs //$user:$pass@$server/$share $dir

# ls -l $dir
# ...

umount $dir && rmdir $dir

Method 2

This one only works if a user is logged in. But it has the advantage to mount into the standard /Volumes/$share folder.

open "smb://$user:$pass@$server/$share"

# ls -l /Volumes/$share
# ...

diskutil unmount /Volumes/$share

This method opens a Finder Window in the GUI, showing the mounted share.

Method 3

Like method 2, this only works if a user is logged in, and also mounts into the standard /Volumes/$share folder.

However, unlike method 2, it does not open a Finder window to the mounted share. (But it does also create the icon on the Desktop).

It needs cumbersome quoting if using variables, because one cannot use single quotes.

osascript -e "mount volume \"smb://$user:$pass@$server/$share\""

# ls -l  /Volumes/$share
# ...

diskutil unmount /Volumes/$share