mounting a Samba share

The Linux mount command can also access Samba (Windows) shares, but in contrast to the smbclient command it does not do a Netbios based lookup for machine names. So while

smbclient //server/share

will work, the corresponding

mount -t cifs //server/share /mnt/point

will tell you that it can’t resolve the host name (unless you add the host to your hosts file or it can be looked up via dns).

This StackExchange answer pointed me in the right direction:

There is a command for actually doing that lookup. It’s called nmblookup.
It returns the IP address of the server like this:

nmblookup server
192.168.1.234 server<00>

While this is fine for manually looking it up, if you want to mount a share multiple times or in shell script, this won’t do because you need the IP address only, not the suffix after it.

It gets even worse if the machine in question has more than one IP address:

nmblookup server2
192.168.1.234 server2<00> 192.168.2.234 server2<00>

Bash to the rescue (I found that solution via this StackOverflow question and this article.)

#!/bin/bash
MACHINE=$1
shift  # Remove machine name from argument list

SHARE=$1
shift  # Remove share name from argument list

# nmblookup the machine
RES=$(nmblookup $MACHINE)
#echo "RES=\""${RES}"\""

# remove everything but the ip address
# note that this will not return anything meaningful
# if nmblookup returns an error (e.g. cannot find the machine)
IP=${RES%% $MACHINE*}
#echo "IP=\""${IP}"\""

# Mount smbclient share (passing any arguments on to smbmount
mount -t cifs -r //${IP}/${SHARE} "$@"

Put this code into a file, e.g.

/usr/local/bin/mount-win-share

and call it like

mount-win-share server share /mnt/point

If you add additional parameters or options, they will be passed on to mount.