- Как примонтировать vdi?
- MNorin.com
- Блог про Linux, Bash и другие информационные технологии
- Использование образов дисков VDI в Linux
- Установка пакета
- Подключение диска
- Параметры командной строки vdfuse
- Похожие посты:
- Использование образов дисков VDI в Linux : 2 комментария
- Open vdi files linux
- Ordeal
- How to Mount a VDI File
- First Your VDI File
- Installing qemu
- Making the VDI Accessible as a Device
- Mounting an LVM System
- Cleaning Up Once Done
- Re: Mounting a VDI disk in your host system to edit the file .
- Re: Mounting a VDI disk in your host system to edit the file .
- Re: Mounting a VDI disk in your host system to edit the file .
- Re: Mounting a VDI disk in your host system to edit the file .
Как примонтировать vdi?
caminati/mount_vdi.html — нифига не работает. +этому скрипту требуется фиксированный образ, что некомильфо.
Какие ещё есть вменяемые способы?(перегонять в img — невменяемый)
Желательно указывать, то, чем вы риально пользовались, а не нагугленные варианты.
Чем же вам в img не вменяемый?
>> Желательно указывать, то, чем вы риально пользовались, а не нагугленные варианты.
Чёто я не понял, а как им пользоваться?Т.е. примонтировать-то примонтировало. но вместо ожидаемой обычной структуры каталогов наблюдаю три каких-то непонятных файла
По обьёму основное EntireDisk
Да-да, уже разобрался. mount -o loop Partition1 надо
Спасибо, этот способ наиболее хороший.
А вот оно всегда в Partition1 или может отличаться?А то неудобно же, cкрипт хочу написать чтоб одним кликом монтировать.
Ну, там та же логика, что и с /dev/sda, sda1-4, 5 — расширенный раздел. Вроде не должно быть проблем с автоматизацией.
Второй вариант — использовать qemu-nbd из qemu-utils (см. How to mount a VirtualBox VDI image). Но предложенный выше вариант с virtualbox-fuse несомненно лучше и удобнее. nbd склонен падать при активном I/O с подмонтированными дисками, почему-то.
Только что смонтировал свой диск от VirtualBox’a (3.2.10 если что) с вендой
mount -t ntfs-3g winxp.vdi /mnt/tmp2 -o loop,offset=65536,force
Как offset вычислять?
В этом образе с 0-го по 64-ый сектор служебная инфа, в 65-ом MBR, в 128-ом начало раздела. 128секторов*512байт=65536байт смещения.
Это видно отличается для разных ф.с./cтpуктур дисков.Ext4 попробовал(ntfs у меня нет) — не монтирует, «wrong fs type, bad option, bad superblock . »
Скрипт из стартового поста, кстати, именно на вычислениях обламывался.
А вот с qemu тоже рабочий способ, в принципе даже более наглядный.
минус — делать modprobe да и учитывая
nbd склонен падать при активном I/O
Вцелом, думаю лучше использовать специально предназначенные для этой цели средства, т.е. fuse.
Это видно отличается для разных ф.с./cтpуктур дисков.
Ничего подобного. Оно зависит от того, как ты разметил виртуальный диск. У меня он размечен установщиком венды, потому сам ntfs-раздел начинается в 63-ем (при счёте с нуля) секторе виртуального диска, а поскольку собственно винт начинается с 64-ого сектора или как-то так (и это либо стандарт, либо в начале диска должно быть указано сколько секторов/байт занимает служебная область), то получается смещение первого раздела в 128 секторов по 512 байт
Если хочешь опробовать монтирование vdi на петле, посмотри в виртуалке разметку виртуального диска с точностью до секторов и выложи сюда, попробуем расчитать (+64), проверить.
И да, петлевая фс ИМХО получше всех этих наблыдокоженных fuse, особенно когда никаких модификаций над считываемыми данными не производится, посекторный образ же лежит, не то что там загзипованный или затаренный.
>> петлевая фс ИМХО получше всех этих наблыдокоженных fuse
Таки оно будет работать с динамически расширяемыми образами?
надо проверить, я никогда не пользовался динамически расширяемыми образами, ставлю статический размер всегда
Если хочешь опробовать монтирование vdi на петле, посмотри в виртуалке разметку виртуального диска с точностью до секторов и выложи сюда, попробуем расчитать (+64), проверить.
Ну, джастофан разве что, для практического использования нет смысла в изобретании велосипедов.
А чем смотреть разметку, fdisk пойдёт?
>ставлю статический размер всегда
Аааа, вот оно что. Наверное в этом проблема, у меня динамические.
А ну если джаст фор фан, погрепай из виртуалки
dd if=/dev/sda | hd -v | grep «55 aa |»
dd if=virtual_machine.vdi | hd -v | grep «55 aa |»
и покажи сравним
Предварительно нужно сделать том статическим vboxmanage clonehd —variant static win.vdi temp.vdi #hd -n 1000000 win.vdi | grep «eb 52 90 4e 54 46 53» | cut -c 1-8 00027e00 Что выдаст это и есть смещение в образе. mount -t ntfs-3g temp.vdi /mnt -o loop,offset=0x27e00
ps Кому трудно запомнить «eb 52 90 4e 54 46 53» это сигнатура .R.NTFS 🙂
big-town , по поводу «ps», прежде чем громко именовать то, по чему ты привык детектировать начало ntfs-раздела, сигнатурой, стоит изучить доподлинно известный формат NTFS бутсектора.
0xeb5290 — это JUMP 52h, NOP — переход к IPL (Initial Program Loader) в этом же бутсекторе по известному смещению 0x52. А действительно OEM-сигнатурой NTFS является совсем не «NTFS», а «NTFS » или в hex’e 4e54465320202020.
//устраиватель цирка по кнопочкам
anonymous — это ты вообще о чем? Всегда «любил» вот таких «правильных выскочек» которые умеют только критиковать. То что eb 52 -это во первых не jump, а jmp 52h я знаю и без тебя, это команды короткого перехода где знаковый бай указывает на смещение на которое нужно перепрыгнуть вперед или назад в зависимости от знака. Первые три байта это действительно команда перехода на загрузочный код, далее следует информация о диске. А смещение в команде монтирования нужно указывать именно где располагаются данные eb 52 90 4e 54 46 53 . Проверяем sudo hd -n 512 /dev/sda1 первые байты какие? Вот то то и оно.
Источник
MNorin.com
Блог про Linux, Bash и другие информационные технологии
Использование образов дисков VDI в Linux
VDI — это формат образов дисков, используемых системой виртуализации VirtualBox. О том, как использовать реальный диск на виртуальной машине, я уже писал, теперь посмотрим, как можно реализовать обратный процесс — использование виртуального диска в реальной системе. Таким образом вы можете получить доступ к данным, находящимся на диске виртуальной машины без необходимости ее запускать. Использование образов дисков VDI в Linux сводится к установке пакета и двухэтапному монтированию, после чего содержимое можно использовать точно так же, как и содержимое любой другой файловой системы.
Для подключения виртуального диска в формате VDI используется программа vdfuse, входящая в состав пакета virtualbox-fuse.
Установка пакета
В Debian/Ubuntu пакет устанавливается командой
Если у вас установлена версия VirtualBox от Oracle, может потребоваться установить по зависимостям VirtualBox OpenSource Edition (virtualbox-ose).
Подключение диска
На первом этапе монтируется образ VDI. Это можно сделать следующей командой:
Таким образом мы получим доступ к разделам, которые присутствуют на виртуальном диске. На втором этапе монтируется необходимый раздел:
После этого можно работать с файловой системой на виртуальном разделе.
Параметры командной строки vdfuse
В общем виде формат выглядит так:
Вот какие опции есть у vdfuse:
Опция | Значение |
-h | Помощь |
-r | Монтировать только для чтения |
-t | Указать тип образа диска (VDI, VMDK, VHD, или raw). Значение по умолчанию — auto |
-f | Указать имя файла образа диска |
-a | Разрешить всем пользователям читать диск |
-w | Разрешить всем пользователям читать диск и писать на него |
-g | Работать как приложение (не в фоновом режиме) |
-v | Выводить дополнительную информацию |
-d | Включить режим отладки |
Похожие посты:
Использование образов дисков VDI в Linux : 2 комментария
да не плохая статья и была бы полезна если бы этот пакет до сиих пор был бы в репозитариях. но к сожалению на дебиан 9 и репозитарии сайта виртуал бокса больше такого пакета не имеют. можэт подскажете альтернативный пакет в стрейче. так бы ваша статья стала актуальной и сейчас. а я пока продолжаю искать актуальные пакеты на сегодняшний день. всего хорошего.
Источник
Open vdi files linux
Ordeal
Today I made a mistake and create the file /etc/sudoers.d/timeout which was definitely not compatible with sudo. The file was JSON when sudo only accepts very basic var=value lines.
I could not use sudo anymore on that VM. I had to find a way to fix the file system without having to rebuild the entire disk because that would have taken way too long.
How to Mount a VDI File
Since your VDI (VirtualBox Disk Image) files are literally disk files, they should be mountable, right? Yes! They are. Actually, that’s certainly exactly what the VirtualBox code does, but somehow we are not provided with a dead easy way (it seems) to do just that.
On my old system I had fuse and used that successfully but somehow with the VDI format, it seems to be confused. So I looked for a different method and there were so many steps that I really need to write them down to find them again.
The steps below work just fine in Ubuntu 16.04 and should continue to work for a while. Other solutions may work using FUSE, but I’ve never been too happy with FUSE.
First Your VDI File
My VDI disk is under my VirtualBox folder, something like this:
Note that in the console you will want to use quotes. At least I think quotes are easier to use than a ton of backslashes. In my full disk names, there are more spaces and parenthesis, so it becomes difficult to read with escaping instead of quotes.
Installing qemu
The file can be mounted using the qemu-nbd virtual device.
If you don’t have it yet, make sure to install qemu on your host machine:
You may only need qemu-kvm , although having the entire environment on your development machine probably won’t hurt.
Making the VDI Accessible as a Device
With qemu-nbd we can now start a virtual disk device this way:
Note: I use /dev/nbd1 instead of /dev/nbd0 because somehow when I use /dev/nbd0 the system does not automatically create the expected three partitions. This may be normal, but when using /dev/nbd1 it works as expected so I am thinking that there is something fishy about /dev/nbd0 .
The nbd device takes over and creates partitions. These are likely going to be named:
Partition 1 can be mounted as is because it is an old Linux type of file system. It is used to boot the Virtual Machine.
Partition 2 is a swap file system. You should not have to do anything with this one. Since it’s a swap partition, try to mount as is will fail. The swap has ways to mount these partitions which use a different type of file system than the default for speed reasons.
Partition 5 is your root drive. This includes /home, /etc, /usr, etc. Pretty much all your files. However, this one partition has code 8E. This means Linux LVM. The LVM part means Logical Volume Manager. This is an advanced partition system which reserves the handling of the physical drive to the base system and only gives you a logical way of partioning the available space. The partitioning handles many aspects of modern hard drive capabilities such as RAID capabilities. For example, if you have two hard drives you can very easily create a partition which is duplicated on both drives (RAID 1) or you can create a very large partition (RAID 5).
The «physical» partition numbers (1, 2, and 5) are managed by the LVM system too when you format your drive, although as far as I know these could be changed.
Mounting an LVM System
Now that we have a device available, we can think about mounting it. The LVM System makes things a little more complicated, but not impossible to handle.
First, we want to be able to run kparts so we need to install it if not yet available:
This tool transforms the LVM partitions into a set of mapped devices which can themselves to mounted.
To transform our physical drive partition 5 shown above into a set of partitions that we can mount, run this command:
The kpartx tool creates mapped devices. These appear under /dev/mapper and their respective names:
Here we see a list of physical and virtual devices each representing a partition that can be mounted.
In my case, the one that interests me is:
As we can see it has the base name of the Virtual Machine I created and it says «root» which means the files under «/. «. This is how I found the other set of devices under «snaptest-vg». You can also run the lvdisplay command. There is an example with the out logical volume of interest here:
The mounting here is done as usual with that logical volume of interest:
Now you have full access to the VDI volume from your host computer. Note that in most cases you will need sudo to make any changes on that partition.
Cleaning Up Once Done
It is recommended that you clean up the mounted device once done and especially once ready to run your VM because with two systems writing to the same disk from two completely different interfaces is not unlikely to cause problems and break your VDI disk.
If you don’t want to unmount, run the VM while not using the disk. Shutdown the VM, then do your additional edits. Finally, restart your VM. Again, try to be very careful. (Having your host and your guest both access the same VDI may work, but I suspect there may quirks. attempt such at your own risk.
Just run the steps backward with the opposite command:
It is important to remove the LVM. The lvchange with «-a n» does that for you. If you don’t do that, you get an error as follow from kpartx :
The name you use with lvchange is the group name. In the output of lvdisplay , it is actually the VG Name: . field (VG stands for Virtual Group).
Note that the -d with kpartx doesn’t delete the partition on the disk, it just removes them from the /etc/mapper and other areas.
Similarly, the -d on qemu-nbd just disconnect the device. It won’t hurt your VDI file in any way.
Re: Mounting a VDI disk in your host system to edit the file .
What I wrote worked for me. He! He! What you were trying to do is, I think, sufficiently different that it could fail compared to what I’ve done way back.
Although today’s implementation may have changed, I don’t know, I don’t think it’s changing much as far as the front end is concerned.
What I do on my website, though, is update when I try something again and the old examples do not work quite right. I don’t tweak my drivers much, though.
Re: Mounting a VDI disk in your host system to edit the file .
«These instructions are pretty old [. ]»
«may not work [. ]»
«I’ve not tested [. ]»
«may just not be compatible [. ]»
So. you didn’t test anything. you didn’t offer an alternative either.
Talk is cheap, player.
Re: Mounting a VDI disk in your host system to edit the file .
These instructions are pretty old and may not work properly anymore. I’ve not tested the qemu-ndb in a very long time. It may just not be compatible with the newer version of /dev .
Re: Mounting a VDI disk in your host system to edit the file .
LVM refuses to mount/create directories in /dev. Apparently, after running qemu-nbd, then kpartx, it created two volumes, with identical UUIDs.
nbd1
├─nbd1p1 LVM2_me AxG2cR-lrn7-TcvS-YF2M-bc1T-fY2s-P1hu0m
└─nbd1p1 LVM2_me AxG2cR-lrn7-TcvS-YF2M-bc1T-fY2s-P1hu0m
I’m unable to mount the drive, because it does not create LVM mountable directories.
Источник