Mount qcow2 image linux

Method one: libguestfs

The first way to mount a qcow2 disk image is to uselibguestfsIt provides a set of tools to access and edit VM disk images.libguestfs Support for almost all types of disk images, includingqcow2. You can install it on Linux like thislibguestfs Toolset.

On Debian-based systems:

On Red Hat-based systems:

Oncelibguestfs The installation is complete, you can use it like thisguestmount Command line tool to mount oneqcow2 Disk mirroring. Note that you must not mount its disk image in «read-write» mode while the VM is running. Otherwise, you run the risk of corrupting the disk image. This way, it is always safe to close the disk image of the mounted VM.

guestmount All of the command line argument options are as follows:

We can mount a disk image in qcow2 format like this:

«-m » is used to specify the partition within the disk image that you want to mount (for example, /dev/sda1). If you are not sure what partitions are in the disk image, you can arbitrarily provide an invalid device name.guestmount The tool will show you all the device names you can choose. Such as:

In this example, the optional disk device in the disk image file is only /dev/sda , the file system is vfat 。

For example, to mount a disk image userdata-qemu.img.qcow2 inside /dev/sda , the mount point is qcow2_mount_point , execute the following command:

By default, disk mirroring will be mounted in «read-write» mode. So you can modify it after mounting qcow2_mount_point Any file under the directory.

If you want to mount it in «read-only» mode, then:

To uninstall it, execute:

Note:Mounted above is the qcow2 file generated by the Android emulator. Although the mount can complete successfully, the mount point cannot be accessed after the mount.

Method two: qemu-nbd

Another type of mountqcow2 The method of disk mirroring is through qemu-nbd , a command line tool that exports a disk image as «network block device (nbd)».

You can install it on Linux like this qemu-nbd 。

On Debian-based systems:

On Red Hat-based systems:

To mountqcow2 Disk mirroring, first export the image to nbd ,like this:

First command load nbd Kernel module. The «max_part=N» option specifies that we want to pass nbd The maximum number of partitions managed. The second command exports a specific disk image as a network block device (/dev/nbd0). As a network block device, you can use /dev/nbd0, /dev/nbd1, /dev/nbd2, etc., which are not in use. As for disk mirroring, be sure to specify its «full» path.

For example, to mirror userdata-qemu.img.qcow2 Export as /dev/nbd0 :

Thereafter, if there are multiple partitions in the disk image, the existing partitions in the disk image will be mapped to /dev/nbd0p1, /dev/nbd0p2, /dev/nbd0p3, etc., and the disk itself will be mapped to /dev/nbd0 。

need to check nbd Mapped partition list, then use fdisk :

Читайте также:  Активация windows 10 home ключом windows 10 pro

For the disk mirroring of Android QEMU, its entire image is a file system, and without partitioning, executing the above command will report an error:

Finally, if there are multiple partitions in the disk image, select any partition (for example, /dev/nbd0p1) and mount it to a local mount point (for example, qcow2_mount_point), if it is a disk image like QEMU, the whole Mirroring is a file system that mounts the entire nbd (such as /dev/nbd0).

Now you can pass qcow2_mount_point The mount point accesses and modifies the contents of the mounted partition of the disk image.

Once the operation is complete, you can uninstall it and disconnect the disk image, as shown below.

Источник

Русские Блоги

Как смонтировать образ диска qcow2 в Linux

При запуске гостевой виртуальной машины (ВМ) на уровне виртуализации мы можем создать один или несколько образов дисков специально для этой виртуальной машины. В качестве «виртуального» дискового тома образ диска представляет содержимое и структуру устройства хранения (например, жесткого диска или флэш-накопителя), подключенного к виртуальной машине виртуальной машины. Если вы хотите изменить файлы в образе диска виртуальной машины без запуска виртуальной машины, вы можете «смонтировать» образ диска. После этого вы сможете изменить содержимое образа диска перед его удалением.

В Linux существует несколько способов монтировать образы дисков, и для разных типов образов дисков требуются разные методы. Если вы используете зеркалирование дисков типа qcow2 (используется QEMU / KVM), есть как минимум два способа смонтировать их в Linux.

Метод 1: libguestfs

Первый способ смонтировать образ диска qcow2 — использоватьlibguestfs, Он предоставляет ряд инструментов для доступа и редактирования образов дисков ВМ.libguestfs Поддержка практически всех типов зеркалирования дисков, включаяqcow2. Вы можете установить его в Linux вот такlibguestfs Набор инструментов.

В системах на основе Debian:

В системах на базе Red Hat:

однаждыlibguestfs После завершения установки вы можете использовать его какguestmount Смонтируйте один из инструментов командной строкиqcow2 Зеркальное отображение диска. Обратите внимание, что вы не должны монтировать его образ диска в режиме «чтение-запись» во время работы виртуальной машины. В противном случае вы рискуете повредить образ диска. Таким образом всегда можно безопасно закрыть образ диска подключенной виртуальной машины.

guestmount Все параметры параметров командной строки следующие:

Мы можем смонтировать образ диска в формате qcow2 следующим образом:

«-m » используется для указания раздела, который вы хотите смонтировать в образе диска (например, / dev / sda1). Если вы не уверены, какие разделы находятся в образе диска, вы можете произвольно указать недопустимое имя устройства.guestmount Инструмент покажет вам все имена устройств, которые вы можете выбрать. Такие как:

В этом примере единственными доступными дисковыми устройствами в файле образа диска являются: /dev/sda , Файловая система vfat 。

Например, чтобы смонтировать образ диска userdata-qemu.img.qcow2 внутри /dev/sda , Точка монтирования qcow2_mount_point , Затем выполните следующую команду:

По умолчанию образ диска будет смонтирован в режиме «чтение-запись». Итак, после установки вы можете изменить qcow2_mount_point Любой файл в каталоге.

Если вы хотите смонтировать его в режиме «только для чтения», то:

Чтобы удалить его, выполните:

Заметка:Файл qcow2, созданный эмулятором Android, смонтирован выше. Несмотря на то, что монтирование может быть выполнено успешно, к точке монтирования нельзя получить доступ после ее монтирования.

Метод 2: qemu-nbd

Другое креплениеqcow2 Метод зеркалирования диска через qemu-nbd , Инструмент командной строки для экспорта образа диска как «сетевое блочное устройство (nbd)».

Вы можете установить его в Linux, как показано ниже qemu-nbd 。

В системах на основе Debian:

Читайте также:  Windows для asus pc900

В системах на базе Red Hat:

Смонтироватьqcow2 Зеркальное отображение диска, сначала экспортируйте зеркальное отображение в nbd ,как это:

Загрузка первой команды nbd Модуль ядра. Параметр max_part = N указывает, что мы хотим передать nbd Максимальное количество управляемых разделов. Вторая команда экспортирует определенный образ диска как сетевое блочное устройство (/ dev / nbd0). В качестве сетевого блочного устройства вы можете использовать неиспользуемые / dev / nbd0, / dev / nbd1, / dev / nbd2 и т. Д. Что касается зеркалирования диска, обязательно укажите его «полный» путь.

Например, чтобы отразить userdata-qemu.img.qcow2 Экспорт как /dev/nbd0 :

После этого, если в образе диска есть несколько разделов, существующие разделы в образе диска будут отображаться как / dev / nbd0p1, / ​​dev / nbd0p2, / dev / nbd0p3 и т. Д., А сам диск будет отображаться как /dev/nbd0 。

Нужно проверить nbd Список сопоставленных разделов, используйте fdisk :

Для зеркального отображения диска Android QEMU все его зеркальное отображение является файловой системой, и если раздел отсутствует, выполнение указанной выше команды сообщит об ошибке:

Наконец, если в зеркальном отображении диска есть несколько разделов, выберите любой раздел (например, / dev / nbd0p1) и подключите его к локальной точке монтирования (например, qcow2_mount_point). Если это похоже на зеркалирование диска QEMU, весь Зеркало — это файловая система, поэтому смонтируйте весь nbd (например, / dev / nbd0).

Теперь ты можешь пройти qcow2_mount_point Точка монтирования получает доступ и изменяет содержимое подключенного раздела образа диска.

После завершения операции вы можете удалить его и отключить зеркало диска, как показано ниже.

Источник

Mounting Raw and qcow2 Images

Mounting Raw and qcow2 images in order to inspect and use them doesn’t have to be difficult. After searching the internet, we found a couple of recommendations on how to do it. Here is what we did ourselves on an Ubuntu 16.04 Linux host.

Mounting The Raw Image

Associate the raw image with a loop device:

Map the partitions to loop devices:

You should be able to mount the partitions now:

where /mnt/t01 is a previously-existing mount point or directory.

For LVM partitions, determine the volume group name and activate it:

Mount the desired logical volume:

where /mnt/t02 is another pre-existing mount point or directory.

Unmounting The Raw Image

Unmount the previously mounted partitions:

Deactivate the volume group:

Undo the mapping of the partitions to the loop devices:

Destroy the loop:

Mounting The qcow2 Image

Here, we shall use the QEMU Network Block Device Driver for the purposes of mounting the qcow2 image.

First, load the nbd driver.

Connect nbd to the image using qemu-nbd:

Using fdisk, check the existing partitions. Mount the regular Linux partitions as is:

For LVM partitions, associate a loopback device to the LVM partition:

See the LVM partitions under /dev/mapper:

You should also be able to display the logical partitions using lvdisplay and the volume groups with vgdisplay. Use vgchange as above to activate the volume group.

Mount the regular LVM partitions as usual:

Unmounting the qcow2 Image

Unmount the partitions from the qcow2 image:

Deactivate the volume group:

Remove the loopback device:

Disconnect the nbd device:

Finally, remove the nbd kernel module:

We have successfully used the above procedures in mounting and unmounting raw and qcow2 images used in Linux KVM.

The procedures described above have been adapted for this article from these URLs:

Источник

How to Mount Guest Qcow2 Virtual disk Image containing LVM on KVM Host Machine

For CentOS/RHEL 7

For accessing qcow2 disk image of guest on a CentOS/RHEL 7 KVM host, either use qemu-nbd or libguestfs.

Читайте также:  Html5 для windows phone

Using qemu-nbd

Follow the below steps to mount the qcow2 image in CentOS/RHEL 7 using qemu-nbd.

1. Enable NBD kernel driver on the KVM host.

2. Connect the qcow2 image as network block device.

3. Find the partitions in the image using fdisk

4. The device /dev/nbd0p2, is LVM so you would need to locate the new PVs/VGs and LVs in the KVM host machine.

Refresh the physical volume cache so that host machine recognizes the new PV.

5. Activate the guest OS’es VG.

6. Mount the LVM partition

Once changes are made to the virtual disk image safely disconnect the virtual disk to avoid any issues.

1. Unmount the LVM partition:

2. Deactivate the volume group.

3. Disconnect the image from NBD

4. Remove the NBD kernel driver

For CentOS/RHEL 6

The qemu-image that ships with CentOS/RHEL 6, doesn’t have NBD support. So, for accessing the virtual disk image in CentOS/RHEL 6 KVM host use libguestfs tool.

1. Install libguestfs tools

2. Run the guest filesystem shell

3. Launch the backend using the «run» command.

4. List the filesystems in the image.

5. Exit from guest filesystem shell and mount the partition seen in the disk image.

6. Once done with making changes to the image, unmount it.

Источник

How to mount qcow2 image

I’ve read that with qemu-nbd and the network block device kernel module, I can mount a qcow2 image. I haven’t seen any tutorials on mounting a qcow2 via a loop device. Is it possible? If not, why?

I don’t really understand the difference between a qcow2 and an iso.

5 Answers 5

Thanks to Gilles for pointing out guestmount. Mounting a qcow2 image is very simple on RHEL/Centos/Fedora:

First install guestmount (comes as part of libguestfs-tools in Centos6)

Then you should be able to auto-magically mount your qcow2 image using the -i option

You can manually specify mount points (within the image) using the -m option.
As always read the man page on guestmount for more details.

Note: This only addresses the question title. Please see Peter’s answer for the differences between qcow2 and ISOs.

Step 1 — Enable NBD on the host

Step 2 — Connect the QCOW2 as a network block device

Step 3 — List partitions inside the QCOW2

Step 4 — Mount the partition from the VM

You can also mount the filesystem with normal user permissions, ie. non-root:

Step 5 — After you’re done, unmount and disconnect

A loop device just turns a file into a block device. If the file has some special internal mapping of its blocks, the loop device won’t translate any of it. qcow2 is special. it has special mapping inside that handles different snapshots of the same blocks stored in different places. If you mount that as a loop device, you’ll just get one big block device that doesn’t represent the actual data in the image.

Another option is to convert to raw and mount as a loop device:

But then you have to convert it back to qcow2 to use it again as before.

I think using qemu-nbd is not the most efficient IO, but is easy. Mounting it in a VM, like one booted with a live usb, is easy too. Converting doesn’t make much sense. it was just an example of how they’re different.

Источник

Оцените статью