Как пробросить usb порт на виртуальную машину hyper v

от admin

Проброс USB устройств в виртуальную машину Hyper-V

15.01.2021
useritpro
directoryHyper-V, Windows 10, Windows Server 2016, Windows Server 2019, Виртуализация
commentsкомментариев 14

Одним из существенных недостатков Hyper-Vперед другими гипервизорами (например, ESXi или Proxmox) являются отсутствие полноценной возможности пробрасывать USB устройства с хоста в виртуальные машины. Начиная с версии Hyper-V 2012 R2 появился ряд изменений, касающихся возможностей USB Passthrouth, однако этот функционал все еще уступает возможностям конкурентов. В этой статье мы расскажем об особенностях проброса USB устройств в Hyper-V.

Особенности USB Passthrough в Hyper-V

Под термином USB passthrough понимается возможность проброса USB устройства из хостового гипервизора (или по сети с другого сервера/устройства) в виртуальную машину. С помощью USB passthrough вы можете прокинуть внутрь ВМ токен, USB ключ, модем или любое другое оборудование, подключенное через USB порт.

Плохая новость в том, что в Hyper-V нет нормальной поддержки проброса USB устройств, вы не сможете пробросить любое USB устройство с физического хоста в виртуальную машину (в VMWare с этим на порядок лучше – см. статью USB passthrough в VMWare ESXi). Есть несколько встроенных возможностей использования USB устройства в Hyper-V, но у всех них есть существенные ограничения. На данный момент можно использовать следующие технологии для проброса USB устройства в Hyper-V.

  • Проброс USB дисков с хоста Hyper-V;
  • Расширенные возможности консоли Hyper-V — Enhanced Session Mode;
  • Проброс USB устройства через RDP сессию;
  • Использование программного/аппаратного средства для проброса USB по сети (USB over IP).

Проброс USB диска в виртуальную машину Hyper-V

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

  1. Данная инструкция работает только для USB дисков, которые в системе видятся как fixed, т.е. флешки, смарт-карты и прочие removable-устройства прокинуть внутрь виртуальной машины не получится ( хотя есть небольшой трюк, позволяющий заставить Windows видеть сменное устройство как жесткий диск);
  2. Для таких дисков невозможно создать снапшот/чекпоинт.

перевести usb диск на хосте hyper-v в офлайн

  1. Подключите внешний USB диск к хосту Hyper-V (это может быть как любой хост с Windows и установленной ролью Hyper-V, так и Free Hyper-V Server). Диск появится в системе и ему будет назначена буква диска (если буква диска не назначилась, см. статью);
  2. Откройте консоль управления дисками Disk Management (diskmgmt.msc) на хосте Hyper-V. Щелкните правой кнопкой мыши по диску (левая колонка, в нашем примере USB диск размером 20 Гб имеет идентификатор Disk 1) и выберите Offline.

powershell перевести usb диск в оффлайн

Если у вас используется Windows Server Core или Hyper-V Server, в которых отсутствуют некоторых графические оснастки, вы можете управлять локальными дисками с помощью PowerShell модуля управления дисками. Следующие команды могут вывести список физических дисков на хосте и перевести указанный диск в режим offline: Get-Disk
Get-Disk -Number 1 |Set-Disk -IsOffline:$true

Все! Вы напрямую пробросили внешний USB диск внутрь виртуальной машины Hyper-V и можете его использовать.

Для безопасного извлечения USB диск можно открыть консоль Hyper-V Manager и перейти в окно настроек виртуальной машины. В разделе SCSI Controller выберите жесткий диск, который нужно удалить и нажмите Remove. Сохраните изменения. После этого жесткий диск можно физически извлечь из USB порта хоста Hyper-V.

Проброс USB устройств через Enhanced Session Mode в Hyper-V

В версии Hyper-V, представленной в Windows Server 2012 R2/ 8.1 практически любые USB устройства можно прокинуть внутрь виртуальной машины с помощью технологии Enhanced Session Mode (ESM). Для подключения используется утилита Hyper-V Manager vmconnect.exe . Она позволяет подключится к консоли виртуальной машины и выбрать USB устройства, которые нужно пробросить.

Сначала нужно включить Enhanced Session Mode в настройках сервера Hyper-V. Это можно сделать с помощью PowerShell:

Set-VMHost -EnableEnhancedSessionMode $true

Или в меню Hyper-V Settings -> Enhanced Session Mode.

включить Enhanced Session Mode в hyperv

Перезапустите службу Hyper-V Virtual Machine Management:
Get-Service vmms | Restart-Service

В разделе Integration Services настроек ВМ нужно включить опцию Guest Services.

Для проброса USB устройства через Enhanced Session Mode нужно запустить консоль Hyper-V, выбрать ВМ и нажать Connect. Либо вы можете запустить утилиту vmconnect.exe (Virtual Machine Connection), указать Hyper-V сервер и имя ВМ (утилита поддерживает некоторые параметры командной строки, поэтому вы можете отдавать пользователям настроенный bat файл).

утилита подключения к консоли виртуальной машины vmconnect.exe (Virtual Machine Connection)

Ели ВМ поддерживает Enhanced Session Mode, появится окно, похожее на свойства RDP подключения. Нажмите Show Option -> Local Resources -> Local device and resources -> More.

настройки подключения к ВМ на hyper-v

Выберите USB устройства на вашем компьютере, которое нужно пробросить в ВМ. Если устройства, которое вам нужно, сейчас не подключено, выберите опции Other supported Plug and Play (PnP) devices и Devices that I plug in later.

проброс usb устройства в виртуальную машину hyper-v через enhanced session mode

Теперь все подключённые к вашему компьютеру USB устройства будут автоматически доступны в консольной сессии виртуальной машины Hyper-V.

Основные возможности и ограничения Enhanced Session Mode

  • В качестве гостевых ОС поддерживается только Windows (начиная с Windows 8.1/Windows Server 2012 R2);
  • Вам не нужен прямой доступ к ВМ. Все подключения выполняются через Hyper-V хост (вы подключаетесь к нему через сеть по порту TCP 2179), а подключение к ВМ выполняется через шину VMBus;
  • На компьютере пользователя должен быть установлен Hyper-V Manager

проброс usb через rdp

Данный метод похож на возможность проброса USB устройств через RDP сессию. Мы не будет рассматривать его подробнее.

Методы проброса USB устройства через сеть (USB over IP или в RDP сессии) позволяют сохранить доступ к USB ключу при миграции виртуальной машины на другой хост (Hyper-V Live Migration /vMotion).

Предыдущая статьяПредыдущая статья Следующая статья Следующая статья

page

alt=»Править настройки vhdx диска» width=»58″ height=»56″ /> Как увеличить/уменьшить размер виртуального диска Hyper-V?

Вот из за таких «телодвижений» не люблю использовать hyper-v
Все же должно быть быстро и ясно, что бы протестировать что то на виртуальной системе

«это вам не нужно» отвечу любимой мантрой линуксоидов

Вооще в 2022, ознакомившись с аналогами, и правда не могу представить вариант, при котором обязательно использовать Hyper-V вместо бесплатного Proxmox, у которого возможности на голову выше, в том числе проброс любого устройства или порта USB, в том числе HASP-ключа, для чего в случае с виндовой виртуализацией нужно обязательно покупать отдельную железку/софтину.

Про мантру с вами согласен, но когда имеется альтернатива, похоже и правда «это вам не нужно» =)

Данная инструкция работает НЕ только для USB дисков .
Любые диски, подключенные по SATA, можно подключить в виртуальную машину ( при условии, что их можно перевести в режим OFFLINE )

usb диск не получается сделать offline, нет такой опции

Данная инструкция работает только для USB дисков, которые в системе видятся как fixed, т.е. флешки, смарт-карты и прочие removable-устройства прокинуть внутрь виртуальной машины не получится (

А проброс ключа 1C каким-то образом возможен, кроме USB over Ethernet?

USB-вебкамера так же просто?

Через Enhanced Session Mode не захотела.

У меня не видит флешку. Всё настроил. Сделайте инструкцию по ошибкам и пробросу веб-камеры

Статьи по заказу — по отдельному тарифу ��
ДЛя проброса USB камеры и других устройств можно использовать RemoteFX.
Включить параметр GPO «Allow RDP redirection of other supported RemoteFX USB devices from this computer» в
Computer Configuration > Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Connection Client > RemoteFX USB Device Redirection
Теперь можно подключиться к консои ВМ:
«vmconnect.exe localhost /edit» ->»Show Options», на вкладке «Local Resources» нажать «More» и выбрать камеру в разделе «Other supported RemoteFX USB Devices».
Ну и вот если уж прям совсем подробно:
_https://social.technet.microsoft.com/Forums/windows/en-US/a11eee73-86e0-4782-b2ab-60dfd19556ab/how-to-add-webcam-to-a-hyperv-virtual-machine?forum=win10itprovirt
Enable group policy changes to allow RemoteFX 3D video adapter to work in the HyperV Host
Enable group policy changes to allow RemoteFX 3D video adapter to work in HyperV Client
Enable group policy changes to allow audio to be redirected to HyperV client
Enable group policy changes to allow audio to be recorded from HyperV clientss
Allow enhanced session mode» in hyper manager — server settings
Add RemoteFX 3d Video Adapter in hyperV manager — settings for a given virtual machine
Add the resources to the VM during when a «local resources» menu pops up during boot

На эту страницу я заходил ранее. Эта инструкция для Hyper-V, где он включён как компонент Windows. Вот цитата оттуда: I was able to add my Webcam and USB headset to a VM running on my Windows 10 Pro machine
А у нас гипервизор без GUI, Window Hyper-V Server 2019, который бесплатный, там нет графического интерфейса, это Core. Всё это я пробовал, и ничего не работает. Покажите, снимите видео, где Хайпер-Ви без гуя, и посмотрим, будет ли это работать

Ок, а откуда вы планируете прокидывать USB устройства? По сети или локальные устройства с хоста? По идее при пробросе локальных устройств с самого хоста HV в ВМ все должено работать аналогично

​​Одной из существенных проблем гипервизора HyperV является невозможность пробросить USB устройство в виртуальную машину.

Есть решение этой проблемы — open source проект usbipd-win. С его помощью можно пробросить USB устройство, подключенное к машине под управлением Windows в любую другую по сети, либо в локальный Linux, работающий по WSL2 (инструкция от microsoft).

На базе проекта usbip существует много различных продуктов. Конкретно usbipd-win это только сервер под Windows. Я начал с него, потому что он максимально просто устанавливается и настраивается. Можно через winget поставить:
> winget install usbipd
Либо скачать msi пакет из репы. Далее смотрим список подключенных устройств и публикуем одно из них:
> usbipd list
> usbipd bind —busid=4-3

Опубликованный с помощью этого сервера ключ можно подключить к Linux или Windows машине. Под Linux достаточно установить соответствующие пакеты с утилитой и модулем ядра. Для Debian вот эти:
# apt install usbip hwdata usbutils

После этого можно смотреть список опубликованных ключей и подключать один из них:
# usbip list —remote=10.20.1.56
# usbip attach -remote=10.20.1.56 —busid=4-3

Для подключения этих ключей в Windows, нужно установить Windows Agent. Взять его можно из другого репозитория usbip-win. Там есть инструкция по установке агента. Она немного замороченная, по сравнению с установкой сервера, но ничего особо сложного нет. Вопрос решаемый.

Точно так же можно публиковать USB устройства с Linux по сети на другие машины. Есть пакет сервера и под OpenWRT. Таким простым и бесплатным способом можно решить вопрос проброса USB ключей. Для HASP работает отлично.

Hyper-V USB Passthrough: 3 Alternatives to add USB Support

Hyper-V USB Passthrough: 3 Alternatives to add USB Support

One of the chief features of Hyper-V virtualization is the abstraction of the hardware, including Hyper-V USB passthrough. It focuses on CPU, disk, and memory because all operating systems and applications require them. Even on non-virtualized systems, these resources are shared. Other hardware components present a greater challenge for virtualization because they are not shared, even among separate applications. USB devices fall into that latter group. USB devices expect to communicate with only one subsystem or application at a time. As a result, with Hyper-V USB passthrough, we face special difficulties with USB in virtualized environments.

How to Add Hyper-V Passthrough Support for USB Drives

Hyper-V can set up most USB disk drives in Hyper-V USB passthrough mode, but it does so via Windows’ storage subsystem. As I said in the opening paragraph, only one component can communicate with a USB device, so the Windows disk subsystem brokers I/O for all USB storage devices. For this reason, Windows must identify your USB drive as a “Mass Storage Device” in order for it to connect in Hyper-V USB passthrough mode. Other USB storage devices will not work.

I would like to reiterate that I am fundamentally opposed to permanently mounting any disk in passthrough mode . However, this is a how-to article, so I will show you how to configure Hyper-V USB passthrough. If you have problems, expect all responses from me to be, “I told you so”. I do not have any USB drives to test this with, so my screenshots will not line up well, unfortunately.

    Ensure that the disk is visible in Disk Management. Take it Offline. If the Offline option is not available, the disk cannot be used as a passthrough.
    Offlining a Disk

Offlining a Disk

Add Hard Drive to VM

Hyper-V Cannot Passthrough Non-Disk USB

I often read complaints about the lack of Hyper-V USB passthrough for USB devices. The complaint typically accompanies a negative comparison to applications such as VMware Workstation and Oracle VirtualBox, which can perform USB passthrough. The very sharp distinction to be made here is that Hyper-V is a type 1 hypervisor whereas the products that provide simple USB passthrough are type 2 hypervisors. In a type 2 hypervisor, the management operating system is installed directly to the hardware and the hypervisor is just another application that runs within it. Applications have the ability to exclusively capture a USB port to prevent other applications from using it if they like; this is why it’s so easily done in a type 2 hypervisor. If you’ve ever used a type 2 hypervisor in this way, you’ll notice that they explicitly tell you that the USB device can be attached to the parent or a guest — there’s no sharing or divvying up resource access or anything of the sort. So, the same concepts apply to Hyper-V USB passthrough configuration.

Type 1 hypervisors are not applications. They are kernels firmly entrenched within partitions. A type 2 hypervisor is essentially an application shim that is pretending to provide a root hardware device, which is fine because it doesn’t require the same degree of isolation as a type 1 hypervisor. Hyper-V can’t do this for Hyper-V USB passthrough because one operating system instance locking a USB port from all other operating system instances is just not how type 1 virtualization works. Could there be a way for a type 1 hypervisor to assign a USB port to a specific guest by doing the same thing that a type 2 does? I don’t know. In theory, it sounds like something that could be done. But, technological feasibility is besides the point. Hyper-V doesn’t do it. If you want more information, Microsoft has published a thorough article regarding passing through hardware on the 2016 platform that describes some of the challenges and possibilities, including configuring Hyper-V USB passthrough.

If true Hyper-V USB passthrough is a requirement for whatever you’ve got in mind, then Hyper-V is a poor solution. If you’re using the emulators in Visual Studio, you’re sort of forced into it. For most everyone else, I’d say to turn your eye to a type 2 hypervisor. I personally like VirtualBox . It’s not perfect by any stretch, but the licensing terms are favorable for most and it gets the job done.

Читать:
Data vault что это

All of that said, it is entirely possible to configure Hyper-V USB passthrough inside a Hyper-V guest, even Client Hyper-V.

Note : a fourth option not explored in this article is software-based solutions. I’ve never personally used any, which is why they’re not in the text. Check the comments section, though. Reader Tim has suggested one such application and recounted his own experiences with it.

Should Hyper-V Have USB Passthrough?

This article has had some time to bake in the sun while the world advanced. My thoughts on the subject at initial publication:

First and foremost, Hyper-V is a server-based solution. Beyond that, Microsoft is wholeheartedly embracing cloud concepts, even (in my opinion) to the detriment of a great many other technologies. If you envision a cloud based on virtualization, even an on-premises cloud, you can see fairly quickly that host-based USB is a terrible idea. You never have any guarantee of any kind where a virtual machine will be running from moment to moment. With Shared Nothing Live Migration, even the lack of a cluster no longer locks a virtual machine to a specific host. Host-based USB just doesn’t make a lot of sense in a cloud.

With some time to reflect, I still stand by that view from a server/datacenter/cloud standpoint. But, in the intervening years, far more people have adopted Client Hyper-V and may want to add a Hyper-V USB device. When trying Hyper-V connect USB drive to VM environments, Virtual machines in Windows 10 have substantially fewer mobility concerns. Also, with Hyper-V in Windows 10 users have far more viable reasons to want Hyper-V USB passthrough. However, as you’ll see in the “Method 3” discussion, Microsoft does present a solution that involves offloading the USB connection to its console software. Unfortunately, that has limited applicability.

So, should we expect Microsoft to exert the effort to create a true Hyper-V USB passthrough solution, such as Windows 10 Hyper-V passthrough? I still lean toward “no”, just because it would require a substantial level of effort and the scope of the console solution will eventually match up with the guest operating systems that people use. Let’s look at a few methods covering how to use USB flash drive in Hyper-V.

Method 1: Network-Based USB Solutions

If you need to make a USB device available in your virtualized datacenter, I prefer network-based solutions. Years ago, I used a product sold by Digi . This is not an endorsement per se because I only ever used the one device and have not used any of their current technology, but they’re still around so they must be doing something right. Remember that USB hubs , not ports, match up with operating systems at a one-to-one ratio. Don’t buy a single device with a lot of ports and expect to connect lots of virtual machines.

USB Over Network

USB Over Network

Pros of network-based USB hubs:

  • Can remain connected to their assigned virtual machine no matter where it moves and whether or not anyone is logged in, provided network connectivity remains constant
  • Allows for concentration and management of networked USB devices in administrator-defined locations. For instance, you might purchase a rack shelf and use it to hold all of your network USB hubs, all connected to a switch provisioned just for connecting those devices.
  • A perfect solution for nuisance devices such as licensing dongles.
  • Widest range of host and guest operating system support.

Cons of network-based USB hubs:

  • A 1-to-1 ratio of hubs to virtual machines often means purchasing many empty USB slots
  • Gigabit Ethernet is much slower than USB 3+
  • Unless your wiring, addressing, routing, and firewall infrastructure allows for it, you may not be able to provide physical device access to end-users
  • Drivers for the network-connected USB hub must be available for your guest operating system, as well as for the USB devices plugged into it
  • The guest must be connected to the network (which could be a limiting factor for VMs that you wish to be isolated)

Method 2: Remote Desktop Protocol

Once a virtual machine has an operating system installed, it behaves very much like a physical machine. So, you can enable remote desktop connections in the System properties window:

Enable RDP

Once that’s done, you can connect to it remotely just as you would any other Windows system.

To allow USB devices in an RDP session:

RDP Show Options

  1. Run mstsc.exe at a Run/command prompt.
  2. Click Show Options:

RDP Show Options

RDP Local Resources

RDP Other Devices

Once you click OK and connect to an RDP session on any host, these options will be retained until you change them. There’s also a nifty tool called “Remote Desktop Connection Manager“. It’s kind of buggy and unstable, but its ability to retain many unique connection settings for remote hosts in a hierarchical tree makes it well worth the minor difficulties.

USB Over RDP

Pros of RDP-based USB connectivity:

  • Completely hypervisor independent.
  • Automatically works when RDP connectivity is enabled
  • Can be controlled and limited by group policy
  • Any user with a USB device attached to his or her desktop with RDP access to the virtual machine can use that device within the virtual machine. So, it is not really true Hyper-V USB passthrough, but a means to connect your USB device using the RDP protocol itself.

Cons of RDP-based USB Connectivity:

  • The device is only connected as long as the RDP session is connected
  • Drivers may need to be installed in the target virtual machine
  • This feature was originally designed with printers in mind; may not work with all devices
  • Connection speeds are commonly very slow
  • Because RDP is a requirement, only Windows operating systems are supported
  • You must have network connectivity between the system that is physically hosting the USB device and the guest operating system; TCP port 3389 must be opened on any firewalls

Method 3: Enhanced Session Mode USB Connectivity

The last method is the most reliable but also has the most restrictions. Enhanced Session Mode was introduced with the 2012 version of Hyper-V and was included with Windows 10’s (and Windows 8’s) Client Hyper-V. This technology merges many of the session technologies of RDP into the VMConnect.exe application. If that application name doesn’t ring any bells, Hyper-V Manager and Failover Cluster Manager invoke it when you use the Connect menu item. So, it is like Hyper-V Manager is using USB passthrough to add a Hyper-V USB drive.

Initiating VMConnect

You can also run it directly just by executing vmconnect.exe at a prompt (elevation is typically required).

Simply, VMConnect is Hyper-V’s console application and can perform USB passthrough Hyper-V functions. Like physical systems in a datacenter, Hyper-V virtual machines can run whether you have attached a console or not. Hypervisor console applications provide at least keyboard, video, and mouse functionality. Mature Type 2 hypervisors tend to have very robust consoles. Hyper-V’s client application has not had nearly as much time to develop, so it taps into features of the Remote Desktop client to bring you Enhanced Session Mode, including Hyper-V USB passthrough.

How to Enable Enhanced Session Mode

Client Hyper-V installations automatically enable Enhanced Session Mode. For the server SKUs, you need to enable it manually. Afterward, you need to restart the Hyper-V Virtual Machine Management service (vmms). The quickest way is with PowerShell:

That cmdlet includes the -ComputerName parameter if you’re running it remotely.

If you prefer Hyper-V Manager:

Enabling USB Enhanced Session

  1. Right-click on the host in the left pane. Click Hyper-V Settings.
  2. In the left-side tabs, click Enhanced Session Mode Policy.
  3. Check the box for Allow enhanced session mode and click OK.

Enabling USB Enhanced Session

It is not necessary to enable the Guest services integration service just to enable USB redirection.

How to set USB Options for Enhanced Session Mode

Because Enhanced Session Mode is based on RDP technology, you’ll see familiar settings. Follow these steps to setup USB redirection for a guest:

Enhanced Session Basic Options

    Upon connecting to a virtual machine that can support Enhanced Session Mode with vmconnect.exe, you’ll be shown the following dialog, where you’ll click Show Options:

Enhanced Session Basic Options

Enhanced Session Local Resources

3. Click More. You’ll be presented with the following dialog:

Enhanced Session Device Connections

Enhanced Session Device Connections

4. Any USB devices that you have will appear under the Other supported Plug and Play (PnP) devices branch. You can check those, as well as the Devices that I plug in later box to cover any additional USB devices.

I didn’t show it, but there is a checkbox on the first screen after clicking Show Options that allows you to save these settings for the current virtual machine.

Enhanced Session Mode Notes

Enhanced Session Mode is the most reliable of the three options that I’ve presented, but it comes with a list of caveats.

Pros of Enhanced Session Mode
  • Works across the VMBus, so it can be extremely fast. Still limited by network speed when vmconnect.exe is used against a remote host.
  • Works with Client Hyper-V
  • Does not require network connectivity directly to the guest, only to the host
Cons of Enhanced Session Mode
  • Same cons as the RDP option, listed above, with the exception of the item about network connectivity to the guest operating system
  • Requires Windows 8/Windows Server 2012 or later as the host and guest operating system (or Hyper-V Server 2012 or later as the host)
  • Windows/Hyper-V Server hosts must each be configured to allow Enhanced Session Mode against guests
  • Each guest must be configured per connecting user
  • If drivers are necessary, they’ll need to be loaded into the guest
  • VMConnect requires sufficient privileges against the host, not just the guest. With AzMan being deprecated in 2012 and removed in all later versions, that means at least Hyper-V Administrators membership unless you have access to System Center Virtual Machine Manager
  • Network connectivity between the system that is physically hosting the USB device and the Hyper-V host running the target guest; TCP port 2179 must be opened. If you’ve opted to leave your Hyper-V host out of the domain for whatever reason, there might be additional necessary steps.

Enhanced Session Mode is best used with Client Hyper-V, and is the closest that you’ll get to the capabilities found in type 2 hypervisors. Remember that it is based on RDP technology, therefore it is not truly Hyper-V USB passthrough. You may find that some devices don’t work as well as they do with type 2 hypervisors; others may not work at all.

Hyper-V USB PassThrough Troubleshooting

What if you have tried one of the methods to get Hyper-V USB passthrough to work, and you are having issues? These may include things like the Hyper-V passthrough USB disk doesn’t show up, how to connect USB drive to Hyper-V virtual machine issues, or how to access USB drive from Hyper-V virtual machine.

Note the following Microsoft resources that can help with troubleshooting Hyper-V USB passthrough, such as:

Wrapping Up

Hyper-V provides a wealth of functionality allowing users to effectively use physical hardware devices attached to virtual machines running inside Hyper-V. However, while Hyper-V provides many capabilities allowing users to connect physical devices, some have issues using Hyper-V USB drives in their Hyper-V virtual machines.

As described, Hyper-V is a Type 1 hypervisor that adds additional complexities when accessing USB drives compared to Type 2 hypervisors such as VMware Workstation and VirtualBox. However, it can be accomplished using network-based USB access, Remote Desktop Protocol, and Enhanced Session Mode to allow access to a physical USB device for a Hyper-V virtual machine.

Typically the need to access USB disks is seen with client Hyper-V running on Windows 10 or 11 when a user wants to access files that exist on a USB device that they want to access inside their guest virtual machine. There can still be edge use cases using the Hyper-V role in Windows Server where admins need to present a USB device to a virtual machine running inside Hyper-V. Fortunately, there are options to configure Hyper-V USB passthrough that are effective and easy.

Note: This article was originally published in August 2016. It has been fully updated to be relevant as of May 2022.

Hyper-V и USB в гостевой операционной системе

Оставляя за рамками заметки плюсы и минусы платформ виртуализации, таких, как Citrix, Microsoft и VMware, стоит остановиться на самом частом вопросе, касающегося возможности использования устройств USB в гостевых операционных системах гипервизора Hyper-V.

Принимая во внимание то, что шина USB является последовательной, предоставлять отдельные порты контроллеров USB определенной виртуальной машине не представляется возможным. Поэтому остается вариант либо предоставлять доступ к шине только одной ВМ, что неоправдано дорого, либо нескольким, что не совсем безопасно. У Microsoft и VMware есть, в принципе, штатные механизмы RemoteFX и USB Redirection соответственно. Решения похожи, но у VMware это выполнено более изящно, несмотря на то, что в случае использовани проброса USB в виртуальную машину с хоста придется забыть о динамическом перемещении виртуальной машины. Таким образом, и RemoteFX и USB Redirection накладывают ряд ограничений на сценарии использования данной функциональности. Очевидным решением является применение разработок, использующих принцип USB-over-Ethernet, представленных как в аппаратном, так и в программном исполнении. Безусловно, для каждого конкретного случая необходимо делать выбор в зависимости от требований, но, как правило, аппаратные решения дороги в обслуживании и не всегда могут обеспечить высокий уровень доступности службы. Тем не менее, не стоит сбрасывать их со счетов.

Ниже приведен обновляемый список решений с разделением по варианту исполнения.

Похожие статьи