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/attach_usb.sh. It is small, I'll post it inline:

#!/bin/bash
# /usr/local/sbin/attach_usb.sh
# 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
CONF=$(mktemp)

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

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

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_usb.sh attach $attr{idVendor} $attr{idProduct}"
SUBSYSTEM=="usb",ACTION=="remove",RUN+="/usr/local/sbin/attach_usb.sh detach $attr{idVendor} $attr{idProduct}"

Reload udev, enjoy.


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