Passthrough USB to VM using UDEV

Sometime desired that USB stick connected to physical host will be exposed to running on it guest VM (QEMU/KVM).

Let's see how to achieve this using UDEV

First, create script that will do real work /usr/local/sbin/ It is small, I'll post it inline:

# /usr/local/sbin/
# This script will attach inserted USB device to first running VM

VM=$(virsh list|awk '/running/{print $2;exit}')
[ 'x'"$VM" = 'x' ] && exit
ACTION=$1 ; vID=$2 ; pID=$3
[ 'x'"$pID" = 'x' ] && exit

cat > $CONF << EOFcat
<hostdev mode='subsystem' type='usb'>
<vendor id='0x$vID'/>
<product id='0x$pID'/>

case $ACTION in 
"attach") virsh attach-device $VM $CONF --current ;;
"detach") virsh detach-device $VM $CONF --current ;;

rm -f $CONF

Next, prepare rule itself, create /etc/udev/rules.d/86-usb2vm.rules file with content:

# /etc/udev/rules.d/86-usb2vm.rules
# pass-through USB device to first running VM:
SUBSYSTEM=="usb",ACTION=="add",RUN+="/usr/local/sbin/ attach $attr{idVendor} $attr{idProduct}"
SUBSYSTEM=="usb",ACTION=="remove",RUN+="/usr/local/sbin/ detach $attr{idVendor} $attr{idProduct}"

Reload udev, enjoy.

Updated on Wed Jun 8 19:29:43 IDT 2016 by Oleg Volkov More documentations here