Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save qiuchengxuan/c67c908d9dfe865051f1 to your computer and use it in GitHub Desktop.
Save qiuchengxuan/c67c908d9dfe865051f1 to your computer and use it in GitHub Desktop.
A simple shell script to attach usb device to kvm
#!/bin/bash
IFS=$'\r\n'
array=(`lsusb -v 2> /dev/null | grep "\(Bus\|bInterfaceClass\)" | awk -F ' ' '{if(/Bus/){printf "%s ",$0} else {$1="";$2="-";print $0}}' | grep -o "ID.*"`)
for i in `seq 0 $(expr ${#array[*]} - 1)`; do
echo -n "$i "
echo "${array[$i]}"
done
echo -n "choose usb device: "
id=`echo ${array[$(read)]} | grep -o "[0-9]\+:[0-9]\+"`
virsh list --all
echo -n "enter domain name to attach: "
read domain
tmp=`mktemp`
echo "<hostdev mode='subsystem' type='usb'>" > $tmp
echo " <source>" >> $tmp
printf " <vendor id='0x%s'/>\n" ${id/:*} >> $tmp
printf " <product id='0x%s'/>\n" ${id/*:} >> $tmp
echo " </source>" >> $tmp
echo "</hostdev>" >> $tmp
virsh attach-device $domain $tmp
rm $tmp
@qiuchengxuan
Copy link
Author

require libvirt & usbutils

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment