How to automatically mount a folder and change ownership from root in virtualbox

Solution 1:

If you have the guest additions installed, use the VirtualBox menu:

Devices > Shared Folders...

Add the path, name and enable "Auto-mount" and "Make permanent" options.

Finally add your user to the group with:

sudo usermod -G vboxsf -a myusername

Logout and back again or reboot the machine to complete the process (thanks @Fo).

Groups are stored in /etc/group, according to the usermod man page.

Solution 2:

Ah the curse of writing a question and then finding the answer immediately after.

I didn't use the full command suggested in this link

sudo mount -t vboxsf -o uid=$UID,gid=$GID share ~/host

So to add ownership and automatically mount in virtualbox via vboxsf in Ubuntu add to the /etc/rc.local file before the exit 0 line the command as follows:

mount -t vboxsf -o uid=1000,gid=1000 <folder name given in VirtualBox> /home/<user>/where/ever/you/want

Solution 3:

Another alternative is to first configure the shared drives in Auto-mount mode like in the first part of @Katu's answer. This will allow to get the mount configurations of the shared drives by running mount. You'll get something like:

$ mount
...
vbox-shared-dir on /media/sf_vbox-shared-dir type vboxsf (rw,nodev,relatime,iocharset=utf8,uid=0,gid=998,dmode=0770,fmode=0770,tag=VBoxAutomounter)...

One can then use this information to update /etc/fstab/ with an additional line, replacing UID and GID accordingly and removing the tag option:

vbox-shared-dir   /media/sf_vbox-shared-dir  vboxsf rw,nodev,relatime,iocharset=utf8,uid=<UID>,gid=<GID>,dmode=0770,fmode=0770 0       0

After this you should be able to mount the volume automatically running the command:

# mount vbox-shared-dir

Then you just need to remove the Auto-mount option in the virtual box configuration because the volume gets mounted automatically during boot.