Helmut Granda
Helmut Granda

Reputation: 4705

Connect to SMB Server over command line

What is the equivalent to "Connect To Server" on the mac for the command line?

Connect to Server

I would like to automate the process rather than summon the dialog every time I need to connect to a server.

Upvotes: 8

Views: 22009

Answers (2)

Matt Byrne
Matt Byrne

Reputation: 5147

For those who have tried mounting without sudo and keep getting File exists error unless they use sudo, then it may be that you already have this drive mounted somewhere. For me the drive was already mounted through Finder.

Steps to fix:

  • Go to Finder an unmount any manually mounted drives you had there while experimenting. You can also check this via command-line.

    # Don't add the // part to your grep, because username, etc may be added as prefix
    mount | grep some/network/drive
    
  • Run your command again without sudo, making sure the target dir exists, and it should work.

    rm -rf ~/tmp/foo
    mkdir -p ~/tmp/foo
    mount_smbfs //some/network/drive ~/tmp/foo
    

Here is a script that will automate the steps to:

  • Unmount any existing mounts to the same target but with a different mount directory
  • Only mount if not already mounted with same directory
  • Verify user can ls (ignoring stdout, but will show stderr if there is an issue)
#!/usr/bin/env bash
set -e

# Change these two to suit
TARGET_DRIVE="//some/network/drive"
MOUNT_POINT="~/tmp/foo"

ABS_MOUNT_POINT=$(realpath $(eval echo ${MOUNT_POINT}))
# Add <user>@ after the '//'
TARGET_DRIVE_WITH_USER=$(echo "${TARGET_DRIVE}" | sed "s|^//|//${USER}@|")

MOUNTED_PATH=$(mount | grep -e "${TARGET_DRIVE}" -e "${TARGET_DRIVE_WITH_USER}" | awk '{print $3}')
if [ "${MOUNTED_PATH}" != "${ABS_MOUNT_POINT}" ]; then
  if [ -n "${MOUNTED_PATH}" ]; then
    echo "${TARGET_DRIVE} is mounted at ${MOUNTED_PATH}. Unmounting..."
    umount "${MOUNTED_PATH}"
  fi

  mkdir -p ${ABS_MOUNT_POINT}
  echo "Mounting ${TARGET_DRIVE} to ${ABS_MOUNT_POINT} ..."
  mount_smbfs ${TARGET_DRIVE} ${ABS_MOUNT_POINT}
fi

ls ${ABS_MOUNT_POINT} > /dev/null
echo "✓ Verified ${ABS_MOUNT_POINT} mounts to ${TARGET_DRIVE}"

Upvotes: 0

hrishikesh chaudhari
hrishikesh chaudhari

Reputation: 906

There are multiple ways to connect to remote server! I am assuming you have server running on Windows. Mac OS X includes the SMB protocol for networking with Windows computers; some Linux and Unix systems can also share files with this protocol as well. You can easily mount a shared SMB volume using the mount command. Follow these steps:

mkdir /temp
chmod 777
mount -t smbfs //username@ip/nameOfSharefolder /temp

After this you can browse to/temp directory and browse.

You can also use ssh or ftp command to access the remote server but you need to run the ftp server in case of ftp command or remote access must be enabled in case of ssh.

Upvotes: 5

Related Questions