DEV Community

Cover image for Raw VM Image Mounting with losetup
Mathieu K
Mathieu K

Posted on

Raw VM Image Mounting with losetup

I use Qemu/KVM for most of my custom virtual machine, and sometime, I need to do some backup or to check the filesystem from the host point of view. The process is quite simple, the virtual disk is used as a virtual storage device and then we mount the partition on the host. On FreeBSD, we use mdconfig, on OpenBSD we use vmconfig and on Linux, we are using losetup. Both of these commands have the same goal: allocate a special device pointing to a file present on a filesystem. Here an example with losetup.

First we want to mount the image /path/to/your/image.raw on a free losetup device (usually present in /dev/loop*). The --find flag will look for the next available loop device, the --show will print it to stdout and -P will reload the partition table.

# use available loop device, and attach image.raw to it
loop=$(losetup --find --show -P /path/to/your/image.raw)
Enter fullscreen mode Exit fullscreen mode

Then, we can check if the partitions are present (or not). The attached device has been put into the loop variable.

# check the loop devices partition
ls -l ${loop}*
Enter fullscreen mode Exit fullscreen mode

If you are using lvm (it was my case for this note), simply use lvscan command and automatically enable the logical volume found.

lvscan -a y 
Enter fullscreen mode Exit fullscreen mode

mount the logical volume on your and do what you have to do.

mount /dev/vg/lv /mnt

# Do your stuff here.
Enter fullscreen mode Exit fullscreen mode

When you have done, you can simply umount the partition...

umount /mnt
Enter fullscreen mode Exit fullscreen mode

... and finally detach the loop device.

losetup --detach ${loop}
Enter fullscreen mode Exit fullscreen mode

Note: this procedure can be used only for raw qemu image. If you are using qcow format or another one, you will first need to convert it with qemu-img or use a tool like mount-qcow2-image.


Cover Image by Aleksandr Popov on Unsplash

Top comments (0)