Mounting a kvm image on a host system
Needed to mount a KVM disk image on a host system without booting the guest. I’ve used kvm-nbd in the past, but that’s more for exporting a filesystem from a remote server (and, in any event, we now use Sheepdog for distributing VM images around).
Found a number of references to using losetup but wanted something simpler; doing the loop part automatically has been a “take for granted” thing for years.
It turns out that if your image is in kvm-img‘s “raw” format already then you can pretty much access it directly. We found this article, dated 2009, which shows you can do it pretty quickly; assuming that the partition is the first (or only one) in the disk image:
# mount -o ro,loop,offset=32256 dwarf.raw /mnt
#
which does work!
I’m a bit unclear about the offset number; where did that come from?
An earlier post mentioned something called kpartx. Given a disk, it will identify partitions and make them available as devices in via the device mapper. Neat. Hadn’t run into that one before.
This comment on Linux Questions suggested using kpartx directly as follows:
# kpartx -a dwarf.raw
# mount -o ro /dev/mapper/loop0p1 /mnt
#
Nice.
Incidentally, later in that thread is mention of how to calculate offsets using sfdisk -l, however that doesn’t help if you don’t already have the disk available in /dev. But you can use the very same kpartx to get the number of cylinders:
# kpartx -l dwarf.raw
loop0p1 : 0 16777089 /dev/loop0 63
#
Ah ha; 63 sectors × 512 byte block size is 32256. So now we know where they got the number from; adjust your own mounts accordingly. :)
AfC
Comments:
- Pádraig Brady wrote in, saying “I find
partxis overkill. I’ve been using the following script for years;lomount.sh dwarf.raw 1 /mntis how you might use it.” Interesting use offdisk, there.
