ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.
VirtualBox is a popular open-source virtualization software that allows you to create and run virtual machines (VMs) on your computer. While virtual machines provide many benefits, such as increased security and flexibility, there are times when you may need to use a physical hard drive with your VM.
Though it’s possible to create a virtual hard disk image from the existing contents of a physical drive, you might find it useful to directly mount or boot a physical drive on a VM.
And while this is fairly easy to do with the GUI of VMware and Hyper-V when configuring a VM, that isn’t the case with creating a VirtualBox physical disk, or a VirtualBox raw disk, in VirtualBox, as the process requires some command-line interface (CLI) usage.
VirtualBox can mount entire physical hard disks as well as only selected partitions of a drive. This tutorial will only discuss mounting entire VirtualBox physical hard disks.
How to Enable VirtualBox Raw Hard Disk Access
This method is called VirtualBox “raw hard disk access.” This allows you to mount or boot additional storage such as a secondary hard drive or external USB. We’ll show how to do this when running VirtualBox on a Windows, Linux, or macOS host machine.
Warning: Do not attempt to mount or boot the partition that runs the host OS with a VM, as that can lead to severe data corruption. And no matter which drive or partition you want to mount, it’s always a good idea to back up any existing data on it before continuing.
You’ll first want to create a VM within the VirtualBox GUI. Choose all options as normal, but when asked about the virtual hard drive, select Do not add a virtual hard drive.
Next, you’ll need to find the path and drive number of the physical drive you’d like to mount:
- In Windows, open Disk Management. You’ll see the associated drive numbers on the left and will identify them later as PhysicalDrive0, PhysicalDrive1, etc.
- In Linux, run the following command:
sudo fdisk -l
. You’ll see a listing of the partitions. Make note of the desired drive in the format of dev/sda0, dev/sda1, etc. - In macOS, use the following command:
diskutil list
. You’ll see a listing of the partitions. Make note of the desired drive in the format of /dev/disk0, /dev/disk1, etc.
Now open the CLI of your OS. If you’re using Windows as the host OS you will also need to go to the root directory of VirtualBox using the following command: cd C:Program FilesOracleVirtualBox
Creating the VirtualBox Hard Drive
Now you can run the command to create the virtual hard drive file that points to your desired physical drive. For each of the following examples, ensure that you input the desired names between the arrows and replace the number or pound sign with your desired drive number.
Windows:
VBoxManage internalcommands createrawvmdk -filename "C:Users<user_name>VirtualBox VMs<VM_folder_name><file_name>.vmdk" -rawdisk .PhysicalDrive#
Linux:
VBoxManage internalcommands createrawvmdk -filename "</path/to/file>.vmdk" -rawdisk /dev/sda
macOS:
VBoxManage internalcommands createrawvmdk -filename "</path/to/file>.vmdk" -rawdisk /dev/disk#
This VMDK will be a very small file that simply points to your physical drive. Now you can attach the VMDK to your VM. To do so, open the VirtualBox GUI, select the desired VM, click Settings, click Storage, click the Add Hard Disk button, select Choose existing drive, and then select the VMDK file you just created.
You can now run the VM that will boot from the physical drive you defined when creating the VMDK file.
If you need additional help you can refer to the official VirtualBox documentation on this topic.
Why You Might Want to Use a Physical Hard Drive with VirtualBox
There are several reasons why you might want to use a physical hard drive with VirtualBox, such as retaining your old OS and data as you move to a new system, isolating two OS versions, or simply because it offers better flexibility and compatibility.
Retention of old OS and data
You can retain an old OS and data by using VirtualBox with a physical hard drive, creating a VM that runs the previous OS and accessing the data stored on the physical hard drive.
This can be useful if you have an old computer with essential data that you want to keep but can no longer use due to hardware failures or other issues. By using VirtualBox with a physical hard drive, you can create a VM that runs the old OS and access the data stored on the physical hard drive.
Isolation of OSs
For security reasons, you may want to avoid a situation where you will be transferring files between your hard drive and VM. By using VirtualBox with a physical hard drive, you can create a VM that runs an OS or application in isolation, which can help prevent conflicts or security issues on the host system.
Better compatibility
Some OSs or applications may not work correctly with virtual hard drives, but can work seamlessly when installed on a physical hard drive and accessed through VirtualBox. By installing such applications on your physical hard drive and accessing them through your VirtualBox, you can avoid these compatibility issues and ensure that everything continues to run smoothly.
Provides flexibility
Using a physical hard drive with a VirtualBox provides more flexibility in using your computer. For example, you can run multiple OSs on your computer simultaneously, which can be useful if you need to test software or if you need to use different OSs for other tasks. You can also use your computer as a test environment for software development, which can help you avoid conflicts with your main OS and applications.
Risks of Using a Physical Hard Drive in VirtualBox
Although using a physical hard drive in VirtualBox VM has a lot of benefits, it comes with some risks. These include data loss, security concerns, and compatibility and performance issues.
Possibility of data loss
If the physical hard drive is not properly configured for use with the VirtualBox VM, it may cause data loss or corrupt your files. For instance, if the physical hard drive is not set up correctly to work with the VM, it may not be able to handle the volume of data being transferred between the host OS and the VM. This can result in data loss or corruption, which can be difficult to mitigate.
To avoid this risk, it’s important to properly configure the physical hard drive and ensure that it is compatible with both VirtualBox and the guest OS. In other words, it is also a good practice to regularly back up important data before running any virtualization software on your system to prevent data loss of this kind in case something goes haywire.
Security risks
While VirtualBox is built to execute its operations in a protected and isolated environment on the host OS, it does not totally insulate your machine’s hard drive from security risks. When using a physical hard drive with a VM, the VM can get infected with malware, potentially spreading to the host OS through the physical hard drive.
This is the case for many computers with the addition of the MMU virtualization feature to their processors, which allows direct memory access (DMA). This addition allows guest VMs like VirtualBox to directly access peripheral devices, such as accelerated graphics cards, Ethernet, and hard-drive controllers, through interrupt remapping, also known as PCI passthrough. To mitigate this risk, it’s important to ensure that the VM is properly secured and running up-to-date anti-malware software.
Compatibility issues
You might run into compatibility issues when trying to run VirtualBox on some OS versions. For instance, in a statement, Microsoft acknowledged that users experienced compatibility issues when running VirtualBox on Windows 11. Although Microsoft has provided some updates to resolve this compatibility issue, it is illustrative of the importance of ensuring that the hard drive and OS version are compatible with the VirtualBox.
You should consider going through the VirtualBox end-user and technical documentation pages to ensure your physical hard drive and OS meet the requirements.
Performance risks
Using a physical hard drive with a VM may result in reduced performance, particularly if the host and guest OSs access the physical hard drive simultaneously. If you have such a scenario, you risk causing delays or other issues that can affect the user experience.
To avoid this type of experience, consider using a physical hard drive with high-performance specifications, such as a solid-state drive (SSD). Configure your VM to limit the amount of data transferred between the host and guest OSs. You should also avoid running resource-intensive applications simultaneously on the host and guest OSs.
Bottom Line: Using a Physical Drive with a VirtualBox VM
Using a physical hard drive with a VirtualBox VM can be a useful way to access data stored on a separate disk, run multiple OSs, and enjoy flexibility on your computer. However, it is essential to note that some limitations and risks are associated with that.
One of the main limitations is the risk of data loss or file corruption if the physical hard drive is not properly configured when using it with the VM. It is also worth noting that using a physical hard drive with a VirtualBox may require advanced technical knowledge and may not be suitable for beginners or those unfamiliar with virtualization technology.
Therefore, in addition to going through the VirtualBox documentation page, it‘s recommended that you have a good understanding of virtualization, disk partitioning, and file systems before attempting to use a physical hard drive with a VM.
If you’re considering other virtualization options, we reviewed the best server virtualization software for various use cases.
При использовании системы виртуализации VirtualBox чаще всего используют виртуальные диски. Они дают возможность гибко распределять дисковое пространство и выделять гораздо больше дискового пространства, чем у вас реально есть. Однако использование физического диска в VirtualBox имеет как минимум одно явное преимущество — это скорость работы. Кроме того, с реального диска операционную систему при желании можно запускать как в виртуальной машине, так и на реальном железе.
Самое первое, что нужно сделать — это создать раздел на жестком диске, либо подключить еще один жесткий диск, с которым виртуальная машина будет работать.
После этого необходимо создать особенный виртуальный диск, который будет работать с физическим диском.
Создание виртуального диска, указывающего на физический
Вот пример для настоящего физического диска, который будет использоваться в качестве диска виртуальной машины.
В Linux это делается командой:
VBoxManage internalcommands createrawvmdk -filename drive.vmdk -rawdisk /dev/sdb
Для выполнения этой команды могут потребоваться права суперпользователя. Таким образом мы получим файл drive.vmdk, который будет указывать на диск /dev/sdb, подключенный к физической машине.
В Windows это будет выглядеть несколько по-другому. Физический диск там указывается несколько по-другому, но смысл будет абсолютно идентичный:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" internalcommands createrawvmdk -filename C:\VMs\testvm\drive.vmdk -rawdisk \\.\PHYSICALDRIVE1
Подключение диска к виртуальной машине
Выбираем виртуальную машину, нажимаем Ctrl+S (или кнопку Settings), выбираем «Storage» -> «Controller: SATA», нажимаем левую кнопку из тех, что расположены ниже.
Выбираем «Add Hard Disk» и в появившемся диалоге выбираем созданный ранее жесткий диск:
И нажимаем «Open». Предварительно может понадобиться включить текущего пользователя в группу, имеющую доступ к этому устройству на чтение и запись (группа может называться например «disk»). Теперь надо изменить режим доступа. Открываем в меню «File» -> «Virtual Media Manager». Выбираем наш диск и нажимаем кнопку «Modify»
Выбираем режим доступа «Writethrough»
После этого нажимаем «OK», затем «Close». В качестве загрузочного носителя в настройках виртуальной машины можно выбрать жесткий диск.
После этого виртуальную машину можно запускать и устанавливать операционную систему.
Если вы используете логический диск, на котором операционная система уже установлена, то загрузка скорее всего завершится неудачей, поскольку при загрузке не будет найдена таблица разделов.
.vmdk, Add Storage, Debian, Disk, Hard Disk, Hard Drive, HDD, How To, Hypervisor, i12bretro, SSD, Storage, Tutorial, VDI, Virtual Disk, Virtual Disk Image, Virtual Machine, Virtual Machines, VirtualBox, VirtualBox Add Physical Storage, VirtualBox Hardware Passthrough, Virtualization, VM, Windows
1 Minute
View interactive steps on GitHub
Creating the Physical Disk VMDK
- Connect the physical disk to the host
- Log into the VirtualBox host
- Launch PowerShell as administrator
- Run the following commands
# list physical disks
Get-PhysicalDisk - Take note of the disk number for the target disk to mount in VirtualBox
- Continue with the following commands
# cd to the virtualbox installation directory
cd «$ENV:ProgramFiles\Oracle\VirtualBox»
# create a vmdk disk pointing to the target physical disk
# usage
# .\VBoxManage.exe internalcommands createrawvmdk -filename «<%fullpathto.vmdk%>» -rawdisk \\.\PhysicalDrive<%disknumber%>
.\VBoxManage.exe internalcommands createrawvmdk -filename «D:\VMs\SSD.vmdk» -rawdisk \\.\PhysicalDrive2
# launch virtualbox manager
.\VirtualBox.exe
Attaching the Physical Disk to a Virtual Machine
NOTE: If you don’t run VirtualBox Manager as administrator you will get permissions errors trying to access the physical disk
- Right click on the target VM > Settings
- Select Storage from the left navigation menu
- Click the Add Hard disk icon
- Click Add > Browse to and select the .vmdk file created earlier
- Scroll to the bottom of the listing and select the .vmdk > Click Choose
- Click OK to confirm the VM settings
- Right click on the target VM > Start
Documentation: https://www.virtualbox.org/manual/ch09.html#rawdisk
Published
Running VirtualBox with an external hard drive is a great way to extend the functionality of your virtual machine. Users can enjoy multiple benefits when they mount a USB hard drive in VirtualBox. However, there are some limitations and potential risks you may encounter. You need to know how to mount an external hard drive in VirtualBox efficiently. This article talks about how to create a hard drive in VirtualBox, the advantages of using an external storage device, and some of the problems you need to avoid.
Contents:
- Why to work with external hard drive in VirtualBox.
- Use Extention pack to enable hard drive in VirtualBox.
- VirtualBox Raw Hard Disk Access
- Try the software to access external Hard drive
- The risks you can face when mount an external hard drive to VirtualBox.
The reasons to mount an external hard drive in VirtualBox
There are several reasons to mount a hard drive in VirtualBox, such as retaining your old OS and data as you move to a new system, isolating two OS versions, or just increasing productivity and the functionality of your VMs.
- A physical hard drive attached to a VirtualBox VM adds flexibility to your computer. It allows you to run multiple operating systems simultaneously to facilitate software testing or run programs that require a specific environment.
- An external hard drive may be necessary to enable users to run certain applications or operating systems that are incompatible with virtual drives. You can install an alternate OS or applications on a physical drive and then access and run them from VirtualBox to eliminate compatibility issues.
- You can make an old operating system and its data available from a VM by using an external hard drive to store the data and code from the previous OS. Users can access the old OS through VirtualBox.
- Implementing a physical hard drive with VirtualBox lets you isolate an operating system or application, minimizing possible security concerns. Sensitive data can remain on the external drive rather than being transferred to a virtual drive that may be less secure.
VirtualBox Raw Hard Disk Access
There are multiple methods of accessing the data on a hard drive from within virtual environments. One option is to use the contents of a physical drive to create a virtual hard disk image. At times, it may be more beneficial to mount or boot a physical hard drive directly from a guest VM.
VirtualBox enables you to mount all or part of a hard drive. You can designate specific partitions to be mounted or choose to use the complete disk. We will be discussing the method known as VirtualBox raw hard disk access. This is where the whole VirtualBox physical hard drive is mounted. The advantages of this method include giving users the ability to boot their system from an external USB drive or additional hard disk.
We will demonstrate how to accomplish this on Windows, Mac OS X, and Linux host operating systems.
Note: You should always backup your data before attempting to mount drives or partitions in your virtual machine. Avoid mounting or booting the partition running the host operating system, as it may result in substantial data corruption.
The VMDK that is created is a small file that acts as a pointer to the physical hard drive. To use the disk, you just attach the VMDK to your virtual machine. Perform the following steps after opening to VirtualBox GUI.
- Select the desired virtual machine that will access the disk.
- Click “Settings > Storage > Add Hard Disk”.
- Select the “Choose existing drive” option.
- Choose the VMDK file previously created.
Your virtual machine can now boot from the physical drive associated with the VMDK file.
Начиная с версии 1.4, в качестве альтернативы использования образов виртуальных дисков (описывается подробно в Chapter 5, Virtual storage ), VirtualBox может также предоставить физический жесткий диск или любой выбранный раздел как виртуальный диск для виртуальной машины.
В VirtualBox этот вид доступа называется «raw hard disk access»; он позволяет гостевой операционной системы получить доступ к своему виртуальному жесткому диску без использования файловой системы хоста. Реальная производительность при использовании файлов образов и raw дисков будет различаться, и во многом зависит от файловой системы хоста, использования метода динамического расширения дисков и стратегии кеширования ОС хоста. Кеширования также косвенно затрагивает другие аспекты — такие как отказоустойчивость файловой системе, т.е. будет ли виртуальный диск содержать ошибки после аварийного завершения ОС хоста. Ищите подробную информацию о вашей файловой системе в документации по вашей ОС.
Предупреждение
Использовать «raw hard disk access» рекомендуется только опытным пользователям. Неправильное использование режима может привести к полной потере данных на физическом диске. Самое главное, не пытайтесь загрузить гостевую систему с раздела, с которого в настоящее время загружена ОС хоста. Это может привести к непредсказуемым повреждениям ваших данных.
Доступ через «raw hard disk access» — как ко всему диску так и к отдельным его разделам, — осуществляется через механизм образов диска VMDK. Поэтому, вам придется создать специальный файл VMDK, который определяет, где данные будут хранится. После его создания, вы можете использовать его как обычный виртуальный образ диска. Например, вы можете использовать менеджер виртуалных носителей ( Section 3.5, “The Virtual Disk Manager” ) или VBoxManage
для подключения образа к виртуальной машине.
9.10.1.Доступ ко всему жесткому диску
Хотя этот вариант является самым простым для настройки, вы должны понимать, что это даст гостевой операционной системы прямой и полный доступ ко всему физическому диску . Если ваша ОС хоста operating также загружена с этого диска, будьте предельно осторожны, чтобы не дать доступ полный гостевой системе к системному разделу хоста. С другой стороны, на физическом диске можно изменить структуру или состав разделов, без повторного создания файлов виртуальных образов дисков.
Чтобы создать образ, который представляет весь физический жесткий диск на Linux хосте, используйте команду
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda
Данная команда создаст файл образа /path/to/file.vmdk
(путь должен быть указан полный), для доступа к данным на физического устройства /dev/sda
.
На Windows хосте вместо /dev/sda, указывается MS спецификация устройств, т.е. \\.\PhysicalDrive0
.
Создание образа (физического диска) требует полных прав (чтение и запись) к этому устройству. Полный доступ к нему также необходим при использовании образа в виртуальной машине.
Так же как с простыми образами дисков, данная команда автоматически не зарегистрирует новый образ в реестре менеджера виртуальных дисков. Если вы хотите это сделать автоматически , добавте опцию -register
:
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda -register
После регистрации вы можете подключить новый образ диска к виртуальной машине
VBoxManage modifyvm WindowsXP -hda /path/to/file.vmdk
После выполнения данной команды указанная виртуальная машина будет грузиться с данного физического диска.
9.10.2. Доступ к отдельным разделам жесткого диска
Данный режим «raw partition support» сильно похож на режим «full hard disk», который описан выше. Однако, в этом случае, в VMDK образе будет содержаться информация о разделах диска. В данном режиме вы можете, например, указать другой образ загрузчика для виртуального жесткого диска без внесения изменений в физический диск. Гостю будет видеть все существующие разделы на физическом диске, однако доступ будет ограничен указанными разделами диска.
Для создания образа «raw partition support» (который будет небольшим по размеру, как было упомянуто ранее), в Linux используйте команду:
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda -partitions 1,5
Как вы видете , эта команда идентична команде создающей образ «full hard disk» , за исключения добавленого параметра -partitions
. В данном примере создается образ /path/to/file.vmdk
и разделы 1 и 5 устройства /dev/sda
будут доступны для гостевой системы.
VirtualBox использует ту же самую нумерацию разделов, что и ваш хост Linux. Поэтому , номера указанные в вышеприведенном примере будут указывать на первый диск первичного раздела и первый диск дополнительного раздела (first primary partition and first logical drive in the extended partition).
На Windows хосте вместо /dev/sda, указывается MS спецификация устройств, т.е. \\.\PhysicalDrive0
. Номера разделов указываются те же, что и в Linux и Windows.
Список номеров разделов вы можете получить командой
VBoxManage internalcommands listpartitions -rawdisk /dev/sda
Вывод этой команды содержит список разделов, их тип и размер, что позволяет пользователю определить нужный раздел.
Образы которые предоставляют доступ к отдельным разделам привязаны к дискам хост системы. Вы не можете передать эти образы на другой хост; также , всякий раз при изменении разделов, образы должны быть пересозданы .
Создание образа (физического диска) требует полных прав (чтение и запись) к этому устройству. Полный доступ к нему также необходим при использовании образа в виртуальной машине. Если это не возможно, имеется особый вариант «raw partition access» (в настоящее время доступен только для Linux хостов) который позволяет избежать предоставления полного доступа ко всему диску текущему пользователю. Для настройки этих образов используйте команду
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda -partitions 1,5 -relative
При использовании в его в виртуальной машине, образ будет представлять не весь диск, а только определенные разделы (в примере /dev/sda1
и /dev/sda5
). Поэтому, полный доступ требуется только к этим разделам, а не ко всему диску. Однако для создания этого образа полный доступ ко всему диску необходим для получения информации о структуре диска.
В некоторых конфигурация возможно потребуется изменение кода MBR создаваемого образа, например чтобы заменить загрузчик Linux, вместо того который используется хостом. Это позволит, например, сразу загрузить гостевую систему Windows, если Linux хост система загружается с «того же самого» диска. С этой целью применяется параметр -mbr
. Он определяет имя файла в котором хранится код MBR. При этом таблица разделов не изменяется, что позволяет использовать один файл с кодом MBR для загрузки с различных разделов. Пример использования:
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda -partitions 1,5 -mbr winxp.mbr
Код из файла MBR будет сохранен внутри образа, а не на диске хоста.
Для всех приведенных выше примерах, вы можете сразу зарегистрировать создаваемый образ в реестре VirtualBox добавлением параметра -register
в приведенные команды. Тогда образ сразу появится в списке зарегистрированных образов дисков в менеджере виртуальных носителей. Пример:
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda -partitions 1,5 -relative -register
сдесь создается образ ссылающийся на разделы диска и в случае успешного его создания регистрирует его в реестре образов дисков.