Wednesday 21 April 2010

Mounting virtualbox shares in a linux (Ubuntu) guest

Mounting VirtualBox shares in a Linux guest is not as straight forward as for a Windows guest. I have only tried this on a Ubuntu guest but I see no reason why it wouldn't work in other flavours.

Some pre-requisites:
  1. Make sure the VirtualBox guest additions have been installed. There are plenty of guides about this
  2. When you create your shared directories DO NOT accept the default name. Use a prefix. For example HostDocuments for the host Documents folders instead of Documents.
    The reason for this is if you use the default name a protocol error will be reported when you mount the shared dir. I don't know why but this small work around fixes the issue
  3. Make sure the vboxvfs module is loaded by adding vboxvfs to the end of /etc/modules

    sudo sh -c 'echo "vboxvfs" | cat >>/etc/modules'
Now we need to allow mounting of vbox shares by normal users.

  1. sudo select-editor and make sure nano is selected. This is a much nicer editor than vi
  2. Now edit the sudoer file using sudo visudo.

    Add the line: %plugdev ALL=(ALL)NOPASSWD:/sbin/mount.vboxsf
    It may be that the group plugdev is a Ubuntu only group. Choose a group that all users belong to. Or create a 'users' group and add the users to it
  3. Create a mounting script in /usr/local/bin.

    sudo nano /usr/local/bin/mountVboxShares

    Paste the following code, but replace the variables at the top and add sections as appropriate.

    #!/bin/bash

    PROJECTDIR="$HOME"/Projects
    PROJECTSHARE="HostProjects"

    DOCSDIR="$HOME"/Documents
    DOCSSHARE="HostDocuments"

    if [ ! -d "$PROJECTDIR" ]; then
    mkdir "$PROJECTDIR"
    fi
    /usr/bin/sudo mount.vboxsf -o uid=`id -r -u`,gid=`id -r -u` "$PROJECTSHARE" "$PROJECTDIR"

    if [ ! -d "$DOCSDIR" ]; then
    mkdir "$DOCSDIR"
    fi
    /usr/bin/sudo mount.vboxsf -o uid=`id -r -u`,gid=`id -r -u` "$DOCSSHARE" "$DOCSDIR"

  4. Allow everyone to execute this script sudo chmod 755 /usr/local/bin/mountVboxShares
  5. Finally add the mount script to the end of the system wide profile script sudo sh -c 'echo "/usr/local/bin/mountVboxShares" | cat >>/etc/profile'