Конфликт Hyper-V и VirtualBox. Ошибка «Не удалось открыть сессию для виртуальной машины. Организация переключения между гипервизором VirtualBox и Hyper-V Virtualbox hyper v на одной машине

29.03.2020 Обзоры 

VirtualBox и Hyper-V являются очень мощными средствами виртуализации. Каждый из них имеет свои плюсы и минусы, и иногда нужно иметь возможность использовать оба гипервизора на одном компьютере. Это реально, несмотря на то, что при активированном Hyper-V запуск виртуальной машины VirtualBox невозможен. Он просто заканчивается вот такой ошибкой.

Тем не менее, благодаря одной хитрости можно заставить их сосуществовать. Для этого надо создать bat-файл следующего содержания:

MS DOS

@echo off cls echo. echo Выберите опции гипервизора Hyper-V при загрузке Windows. Компьютер будет автоматически перезагружен после выбора. echo. echo 1. Включить гипервизор. echo 2. Выключить гипервизор. echo 3. Выход. echo. set /p choice= Ваш выбор: if "%choice%"=="1" goto 1 if "%choice%"=="2" goto 2 if "%choice%"=="3" goto 3 if not "%choice%"=="" echo "%choice%" неверный пункт echo:1 cls echo Включение гипервизора... bcdedit /set hypervisorlaunchtype auto shutdown -r -f -t 10 -c exit:2 cls echo Выключение гипервизора... bcdedit /set hypervisorlaunchtype off shutdown -r -f -t 10 -c "Через 10 секунд компьютер будет перезагружен." exit:3 exit

@echo off

echo .

echo Выберите опции гипервизора Hyper-V при загрузке Windows. Компьютер будет автоматически перезагружен после выбора.

echo .

echo 1. Включить гипервизор.

echo 2. Выключить гипервизор.

echo 3. Выход.

echo .

set / pchoice = Вашвыбор:

if "%choice%" == "1" goto 1

if "%choice%" == "2" goto 2

if "%choice%" == "3" goto 3

if not "%choice%" == "" echo "%choice%" неверный пункт

echo

echo Включение гипервизора...

bcdedit / set hypervisorlaunchtypeauto

shutdown -r -f -t 10 -c "Через 10 секунд компьютер будет перезагружен."

exit

echo Выключение гипервизора...

bcdedit / set hypervisorlaunchtypeoff

shutdown -r -f -t 10 -c "Через 10 секунд компьютер будет перезагружен."

exit

exit

Данный пакетный файл действует очень просто. С его помощью можно временно отключить или включить гипервизор Hyper-V при этом не трогая сам Hyper-V, его файлы и настройки. Виртуальные машины созданные в Hyper-V также останутся в целости и сохранности. В случае необходимости надо запустить созданный нами bat-файл от имени администратора , выбрать нужную опцию и ваш компьютер будет автоматически перезагружен. К сожалению, без перезагрузки обойтись нельзя, но это все равно проще чем каждый раз сносить и ставить снова Hyper-V. Раз, два и как видно VirtualBox замечательно работает и при наличии Hyper-V.

В случае необходимости просто включаем гипервизор Hyper-V и снова пользуемся. Включение или отключение достаточно провести один раз, при последующих запусках Windows будет использовать ранее установленную настройку.

И снова здравствуйте! Эта статья будет полезна для разработчиков, которые используют Xamarin, а также тем кто разрабатывает приложения для Windows и Android устройств используя эмуляторы и нативные средства разработки. Речь пойдет о том как легко и довольно быстро переключаться между гипервизором VirtualBox и Hyper-V.
Небольшое введение. При разработке приложений практически всегда возникает необходимость тестировать их на эмуляторах, так как например Android устройств с различными форм-факторами очень много и хочется убедиться, что приложение будет смотреться приемлемо на всех устройствах. А вот с запуском эмуляторов начинаются различные проблемы, эмулятор android устройств из коробки (стандартный от Google) очень и очень медленный, поэтому рекомендуется использовать сторонний, например Genymotion , который порадовал меня своей скоростью, наверное не уступает реальным устройствам по отзывчивости. Для его использования нужна виртуальная машина (Oracle VirualBox), которая в свою очередь использует свой гипервизор. Гипервизор – это программное обеспечение необходимое для запуска нескольких операционных систем одновременно на одном компьютере. Для разработки под Windows Phone сторонний эмулятор не требуется, стандартный довольно быстрый, но вот для его работы необходимо использовать гипервизор Hyper-V от Microsoft. Два гипервизора не могут одновременно работать на компьютере, поэтому возникает проблема. На блоге англоязычного разработчика я нашел способ решения этой проблемы, который сам сейчас использую, и решил перевести его у себя на блоге.

Итак, теперь собственно о том, как организовать переключение между двумя гипервизорами. Для начала нужно открыть командную строку от имени администратора и написать в ней следующую команду:

C:\>bcdedit /copy {current} /d "No Hyper-V"

C : \ & gt ; bcdedit / copy { current } / d "No Hyper-V"

После успешного выполнения должно появиться сообщение, в котором содержится нужный нам ключ. Далее вводим еще одну команду с ключом, который у нас появился после выполнения первой команды:

После успешного выполнения должно появиться сообщение информирующее что команда выполнена правильно. Вот как все выглядит наглядно:

В принципе все готово, теперь можно переключаться между двумя режимами, но для этого нужна перезагрузка компьютера, что конечно не очень удобно, т.е. чтобы включить или отключить Hyper-V нужно перезагружать компьютер. При загрузке системы теперь будет страница на которой нужно выбрать в каком режиме запускать систему: с гипервизором Hyper-V или без него (т.е. можно использовать гипервизор VirtualBox). Такая же страница отображается, если у вас на компьютере две системы:

Может быть такое, что страница с выбором не будет отображаться при перезагрузке компьютера, это можно настроить, а можно просто нажимать на кнопку перезагрузка в меню windows удерживая клавишу Shift.
На этом у меня все, думаю вам помогла эта статья, всем пока!

In the modern highly virtualized IT world, choosing a hypervisor that is the most suitable for your tasks is an important point. There are multiple virtualization platforms provided by different vendors, and each of them presents attractive features. This blog post explains the differences between Oracle VirtualBox and Microsoft Hyper-V. These two platforms include useful features, in addition to having similarities and differences with which you can familiarize yourself by reading today’s article.

For a complete comparison of VirtualBox vs. VMware, refer to this blog post .

Hyper-V vs. VirtualBox Hypervisor Types

Hypervisor is special software that allows you to run one or multiple virtual machines with their own operating systems (guest operating systems) on a physical computer, which is called a host machine. There are two types of hypervisors – type 1 and type 2.

Hyper-V is a type 1 hypervisor that is also called a bare metal hypervisor, and runs directly on a computer’s hardware. When a physical computer (a host) starts, a Hyper-V hypervisor takes control from BIOS or UEFI. Then, Hyper-V starts the management operating system, which can be Hyper-V Server, Windows, or Windows Server. Virtual machines can be started manually by user or automatically, depending on its settings.

VirtualBox is a type 2 hypervisor that is sometimes called a hosted hypervisor. A type 2 hypervisor is an application that runs on the operating system (OS) and is already installed on a host. When a physical computer starts, the operating system installed on the host loads and takes control. A user starts the hypervisor application (VirtualBox in this case) and then starts the needed virtual machines. VM hosted processes are created.

Hyper-V is always on if the host is powered on, while the VirtualBox can be started and closed by a user on demand.

Windows-Only Hyper-V vs. Multi-Platform VirtualBox

As explained above, Hyper-V can only run on Windows family operating systems. Hyper-V feature is built-in from Windows 8 onwards, and is also available as a server role from Windows Server 2008 to later versions.

Virtual Box can run on a higher number of operating systems such as Linux, Windows, Solaris, and Mac OS. If Windows is used on the physical machines in your environment, you could preference Hyper-V. If your environment is multiplatform, then you can take advantage of VirtualBox and run your virtual machines on different computers with different operating systems.

Support of Guest Operating Systems for Hyper-V and VirtualBox

Guest operating system is the OS that is installed and runs on a VM. A guest OS and host OS may differ. Hyper-V can host VMs with Windows, Linux, and FreeBSD guest operating systems.

VirtualBox supports more guest operating systems than Hyper-V: Windows, Linux, FreeBSD, Solaris, Mac OS, and others. You can see the full list of supported operating systems versions on the official pages of the vendors.

Hyper-V Integration Services vs. VirtualBox Guest Additions

Hyper-V Integration Services is a pack of drivers and utilities that improves overall performance as well as interactions between both host and guest operating systems. Integration Services are installed on a guest OS that runs on a VM. For Windows OS, Integration Services can be installed by attaching a virtual disc image (ISO file) to the VM, which includes the installer, or via Windows Update. As for Linux, main Integration Services are built in kernel of modern Linux operating systems. Integration Services can be updated on Linux when the kernel is updated. As an alternative, you can manually download the full installation package of Hyper-V Integration Services for Linux from the Download Center .

VirtualBox Guest Additions contain system applications and drivers that, similarly to Hyper-V Integration Services, optimize a guest OS as well as improve its performance and usability. Drag & Drop, bidirectional clipboard, automatic resizing, and seamless mode become available after installing Guest Additions. Installation process is similar – attaching ISO disc image with the installer to a VM, and installing Guest Additions using GUI (graphical user interface) or command line.

Virtual Disk Format

The virtual disks of Hyper-V virtual machines are stored as VHD and VHDX files. VHD is an older virtual disk format for Hyper-V. VHDX format has been available since Hyper-V in Windows Server 2012 . There are two types of virtual disk pre-allocation: Fixed and Dynamic.

A fixed virtual disk consumes all provisioned space on storage once the disk has been created. This provisioning type is similar to thick provisioning. Read the blog post about to learn more about virtual disk pre-allocation.

Dynamic virtual disk consumes almost no storage space after creation, and grows over time when the data is written on the virtual disk. This provisioning type is similar to thin provisioning.

VirtualBox supports virtual disks of the following formats: VDI, VMDK, VHD, HDD.

  • VDI is the native VirtualBox format
  • VMDK is VMware virtual disk format
  • VHD is Hyper-V format (VHDX is not supported by VirtualBox)
  • HDD is Parallels Desktop format

You can use fixed size disks and dynamically allocated disks in VirtualBox, similarly to as you can in Hyper-V.

You can convert fixed disks to dynamic disks for both Hyper-V and VirtualBox. Fixed virtual disks need more time for creation and consume more storage space right after creation, but then provide higher performance. Dynamic virtual disks are created near instantly and allow you to save storage space, but their performance is lower than the performance of fixed virtual disks.

Hyper-V Checkpoints vs. VirtualBox Snapshots

Hyper-V checkpoint is a feature that allows you to save a virtual machine state. A checkpoint allows you to revert a VM back to its previous state before unwanted changes were made. There are two types of checkpoints available in the latest version of Hyper-V: Standard Checkpoints and Production Checkpoints. Unlike Standard checkpoints, Production Checkpoints allow you to freeze the VM to prevent write operations on the virtual disk by using VSS (Volume Shadow Copy Service) for Windows-based VMs or File System Freeze for Linux-based VMs. This approach allows you to avoid issues that can occur when Standard Checkpoints are used, such as data inconsistency. Data on a disk must not be changed when a checkpoint is taken. In a case when data is not changed during creating a checkpoint, a snapshot would be data-consistent and application-consistent .

When a checkpoint is created, a differencing virtual disk (AVHD or AVHDX) is created for each VHD (or VHDX) virtual disk of the virtual machine. All changes are written to the differencing disk after checkpoint creation. Differencing virtual disks are stored with parent virtual disks in the same directory.

VirtualBox snapshot is an equivalent of Hyper-V checkpoint. You can save current VM state with snapshots and revert to its previous state if needed. VDI is a native file format of a virtual disk used in VirtualBox. When a snapshot is created, a new differencing virtual disk is created as a new VDI file. When you delete a snapshot that represents an earlier VM state as compared to your current VM state, then a differencing virtual disk is merged with a parent virtual disk, or multiple differencing virtual disks are merged. Be aware that snapshots are used primarily for testing purposes, but not for production purposes.

Note: Checkpoints and snapshots are useful for testing and help you to revert VMs to their previous state. Don’t use them as VM backups. Read our blog post to learn more about the difference between snapshots and backups.

Hyper-V VMConnect vs. VirtualBox Remote Display

Hyper-V Virtual Machine Connection (VMConnect) is a tool that provides access to the GUI or console interface of the virtual machine with which you can manage the VM. VMConnect uses WMI (Windows Management Instrumentation) for this purpose. You can interact with the guest OS of the VM by using a keyboard and mouse similarly to interacting with physical machines. A connection to the VM can be established from the local machine on which Hyper-V is installed and the VM is running, or from a remote machine via the network. VMConnect is usually enabled by default when the Hyper-V role is installed. Otherwise, you can add the Hyper-V Tools feature in Add Features Wizard. Microsoft Remote Desktop Protocol (RDP) is used to establish a connection by VMConnect.

Enhanced session mode allows redirecting local devices and resources to a VM. Clipboard, disk drive, USB flash drive, audio, printer, and display configuration can be redirected. Thus, you can use a USB flash drive inserted into a USB port of your physical machine, in your virtual machine.

VirtualBox also contains tools for the convenient management of virtual machines. VMs that are run on the local machine can be managed with the VirtualBox GUI from the local computer. VirtualBox Remote Desktop Extension (VRDE) is the general extension interface that provides maximum flexibility with extension packages that can be developed by third parties. VRDE is compatible with Microsoft RDP. VirtualBox Remote Display Protocol (VRDP) is provided with such extension packages. This is a backwards-compatible extension to RDP that allows you to use standard RDP clients for controlling remote VMs.

To connect to a remote guest VM, you should type the IP address of the host machine and port set for a remote connection to the VM in the VM display settings. 3389 is the port number used by default. You can set different RDP port numbers for different VirtualBox VMs.

Hyper-V Live Migration vs. VirtualBox Teleporting

Live Migration is a Hyper-V feature that allows you to move running VMs from one Hyper-V host to another transparently, and without significant downtime. This feature is especially useful when you use a Failover Cluster because it helps you provide high availability for the VMs. It is recommended to use a dedicated migration network for Hyper-V Failover Cluster. VM files such as virtual disks must be located on shared storage. If you need to move VM files from one storage to another, then Storage Migration should be used.

VirtualBox Teleporting is a VM migration feature that allows you to move virtual machines from one VirtualBox host to another over a TCP/IP network, even if the VM is running. Source and destination VMs must use the same shared storage. The VM can be transferred from a source host to a target host with minimal downtime, independent from the host OS. For example, you can transfer running Windows-based VMs from a Linux host to a Solaris host or vice versa. Teleporting is available from VirtualBox version 3.1 onwards. Migration of running VMs improves the flexibility of your virtual environment.

Hardware Virtualization and Software Virtualization

Hyper-V supports hardware virtualization. Hardware virtualization is a technology that uses a hypervisor to create an abstraction layer between software and physical hardware for emulating computers. All devices needed for the proper functionality of a computer are emulated with special software. Hardware virtualization must be enabled in UEFI/BIOS on a physical machine.

VirtualBox supports hardware and software virtualization. Software virtualization can only be used for VMs with 32-bit guest operating systems that use x86 architecture. For 64-bit guest systems, only hardware virtualization may be used. Unlike most other virtualization products, due to the support of software virtualization, VirtualBox can run many guest operating systems on computers with old processors, even if those processors don’t have hardware virtualization support.

Remote Management with GUI

Hyper-V Manager is a tool with GUI that helps you to manage your Hyper-V VMs. You can create, import, configure, start, stop, and remove VMs with Hyper-V Manager, as well as perform other actions such as configuring virtual switches, virtual hard disks, creating checkpoints, connecting to the guest OS interface with VMConnect, etc. You can also connect to a remote Hyper-V Server and manage the VMs residing on that server.

phpVirtualBox is an open source tool with a web interface written in PHP that allows to manage remote VirtualBox instances with VMs. phpVirtualBox provides an interface that is the same as the GUI interface of VirtualBox, and as a result, you can manage your VirtualBox instances remotely with a browser, similarly to how you manage your local instances. This tool can be a nice alternative to VirtualBox GUI if you run VirtualBox on a headless server (a server that has OS without GUI).

Remote Management with Console Interface

Hyper-V servers can be managed with PowerShell, which is a Windows command line interface developed by Microsoft. PowerShell is a native tool for Windows, but PowerShell Core is also compatible with Linux and macOS. PowerShell Remoting must be enabled for this purpose. Using PowerShell is a way to automate Hyper-V and VM management , especially in large environments.

VBoxManage is a command line interface (CLI) for VirtualBox. You can access all the features available in the VirtualBox GUI. Moreover, you can access all features provided by the VirtualBox virtualization engine with VBoxManage (not all of the features are available in GUI). CLI can also be used for managing VirtualBox instances on operating systems without GUI (that only have a console interface). Another advantage is the ability of scripting and automating. VBoxManage is compatible with Linux, Windows, Solaris, and Mac OS.

VM Network Traffic Analyzing

Port Mirroring is a network traffic analyzing tool for Hyper-V. This feature allows you to send copies of all received and transmitted packets from one port to another for further packet analysis. The main purpose of using Port Mirroring is troubleshooting. You can create a VM that has a virtual network adapter connected to the appropriate virtual switch> port, install packet analysis software on that destination VM, and send network packets from multiple VMs to the destination VM for analysis.

VirtualBox provides a network tracing feature with which you can enable network packet logging for further analysis. As a result, VirtualBox utilizes the built-in capability and writes all captured traffic of the VM network interface into PCAP files. Later you can open these files in the traffic analysis tool such as Wireshark. This feature can be activated with a command line interface. Disable this feature after finishing investigation to prevent filling out the whole disk with PCAP files.

Shared Folders, Drag & Drop in Hyper-V and VirtualBox

Shared folders are useful for file exchange between different machines. Hence, this approach can be used for copying files from a host OS to a guest OS, and vice versa.

Hyper-V doesn’t include such a built-in feature. You can manually share the folder in your host OS with Windows GUI or PowerShell and provide access to that folder for specified users or groups used in a guest OS. You can also use a Copy-VMFile PowerShell tool in Hyper-V virtual environments as an alternative method to copy files between physical and virtual machines.

VirtualBox includes a built-in Shared Folders feature that can be easily enabled from the VirtualBox user interface. Transferring files between VirtualBox host machine and guest machine by using Shared Folders is convenient. You should open VM Settings, and then select Shared Folders. Add Share: set a folder path (the folder is located on the host machine, for example, C:\temp), enter a folder name that would be displayed in the guest OS. If needed enable or disable the following options: Read-only, Auto Mount, and Make Permanent by checking the boxes. Notice that VirtualBox Guest Additions must be installed on a guest OS.

Drag & drop is a feature for GUI that allows you to move objects such as files or folders from the one part of the screen to another. In context of the virtualization environment, Drag & Drop allows you to move files or folders from a host machine to a guest machine and inversely. Both Hyper-V and VirtualBox products support the Drag & Drop feature.

Hyper-V Integration Services (including Guest Services) or VirtualBox Guest Additions must be installed on a guest OS accordingly. The Enhanced Session Mode must be used when logging on the Hyper-V VM. In VirtualBox go to Devices > Drag & Drop and select the direction (you can select “bidirectional”) to enable this feature.

Conclusion

Both Hyper-V and VirtualBox are attractive solutions for virtualization, and the choice between them may be difficult. Hyper-V is a type 1 hypervisor while VirtualBox is a type 2 hypervisor. Hyper-V can only be installed on Windows-based systems, while VirtualBox is a multiplatform product. Hyper-V supports clustering features such as failover clustering and load balancing. Microsoft virtualization solution would be a good choice for companies that already use Windows -based environment. Oracle VirtualBox is free, supports a high number of guest and host operating systems, and hence, is suitable for multiplatform environments. Today’s blog post has explained the differences between these two virtualization solutions to help you to make the right decision. However, the choice is up to you.

Hyper-V or VirtualBox – Which One to Choose for Your Infrastructure?

5 (100%) 34 votes

Параллельно тестируя их. С утра же, когда устанавливать операционные системы, оказалось, что в VirtualBox вылетает ошибка «Не удалось открыть сессию для виртуальной машины». Код ошибки на скриншоте ниже. Дескать не поддерживается технология виртуализации. Проверил ещё раз настройки BIOS для надёжности - всё в порядке. Настройки VirtualBox и виртуальной машины так же в норме. Оказалось, что просто конфликтуют две программы, а точнее Hyper-V от Microsoft забирал виртуализацию на себя. Решается эта проблема удалением Hyper-V.

Итак, ошибка вот такая:

Удаляем Hyper-V:

Нажимаем Win + R , вводим OptionalFeatures и нажимаем Enter . Или же открываем:

Панель управления ➝ Все элементы панели управления ➝ Программы и компоненты ➝ Включение и отключение компонентов Windows

В открывшемся окне Компоненты Windows снимаем отметку с раздела Hyper-V .

Жмём ОК и перезагружаем компьютер. После этого в VirtualBox необходимо создать новую виртуальную машину и можно начинать с ней работать.

Спасибо, что читаете! Подписывайтесь на меня в социальных сетях Facebook , Twitter , VK , OK и мессенджерах Telegram и TamTam !

Читайте анонсы и посты целиком в

4289

На сегодняшний день VirtualBox является самой популярной бесплатной платформой виртуализации, однако даже у её приверженцев в какой-то момент может возникнуть желании опробовать другие виртуальные машины, в частности, встроенную платформу Hyper-V . Только вот включивший её пользователь очень вскоре обнаружит, что виртуальные машины на его любимом VirtualBox больше не запускаются, а платформа выдаёт ошибку «Не удалось открыть сессию для виртуальной машины» с кодом E_FAIL (0x80004005) .


Причиной ошибки может быть неудачная запись состояния ВМ в файл VBOX , кривое накопительное обновление самой Windows, отключение виртуализации в BIOS , но в данном случае причина кроется в конфликте VirtualBox с Hyper-V . Восстановить нормальную работу виртуалбокс можно удалив компоненты Hyper-V из системы, только вот как быть, если установленные на эту платформу машины вам всё же нужны? Запускать ВМ на одном ПК с включенными VirtualBox и Hyper-V нельзя, но можно временно отключить штатный компонент виртуализации, не удаляя его.

Делается это элементарно. Запустите от имени администратора командную строку или консоль и выполните в ней команду bcdedit /set hypervisorlaunchtype off , а затем перезагрузите компьютер.

Виртуальные машины VirtualBox станут запускаться без ошибок. Чтобы вернуть Hyper-V в рабочее состояние, выполните команду bcdedit /set hypervisorlaunchtype auto и опять же перезагрузитесь.

Для удобства можете создать пакетные файлы с командами и разместить их на рабочем столе.

Кроме того, вы можете добавить режим работы системы с Hyper-V и без него в загрузочное меню.

Для этого в запущенной с повышенными правами командной строке (не PowerShell) выполните команду bcdedit /copy {current} /d «Hyper-V отключена» . При этом будет создан новый элемент в загрузочном меню, а в консоли отобразится его идентификатор (32-значная строка) . Скопируйте её в буфер, замените ею элемент GUID в команде bcdedit /set {GUID} hypervisorlaunchtype off и выполните команду.