Skip to content

Instantly share code, notes, and snippets.

@thexyno
Created November 16, 2019 15:49
Show Gist options
  • Save thexyno/7d3d6acd3a759c92b6408d64dbbfb11d to your computer and use it in GitHub Desktop.
Save thexyno/7d3d6acd3a759c92b6408d64dbbfb11d to your computer and use it in GitHub Desktop.
Script to swap devices when using a virsh VM (useful if you have two sets of keyboards and mice and want to swap between host and vm often)
#!/bin/bash
set -e
virsh='virsh -c qemu:///system'
vm=win10
testdevice=c22d # Mouseman
batchone="$HOME/.config/win10vm/mouseman.xml $HOME/.config/win10vm/g510.xml"
batchonetitle='Mouseman and G510'
batchtwo="$HOME/.config/win10vm/strafe.xml $HOME/.config/win10vm/g502.xml"
batchtwotitle='Strafe and G502'
detachDevices() {
for i in $@; do
$virsh detach-device $vm $i
done
}
attachDevices() {
for i in $@; do
$virsh attach-device $vm $i
done
}
notify(){
notify-send -t 5000 -i keyboard 'VM Device Swap' "$@"
}
startScript() {
if $virsh list | grep -q $vm; then
if $virsh dumpxml $vm | grep -q $testdevice; then
detachDevices $batchone
attachDevices $batchtwo
notify "$batchtwotitle"
else
detachDevices $batchtwo
attachDevices $batchone
notify "$batchonetitle"
fi
fi
}
startScript
@thexyno
Copy link
Author

thexyno commented Nov 17, 2019

The xml files need to look like that

<hostdev mode='subsystem' type='usb' managed='no'>
  <source>
    <vendor id='0x[before the ":"]'/>
    <product id='0x[after the ":"]'/>
  </source>
</hostdev>

The vendor an product ID need to be filled with the USB id, that you can get with lsusb

example:

$ lsusb
Bus 002 Device 004: ID 1b1c:1b15 Corsair Corsair STRAFE Gaming Keyboard
Bus 002 Device 003: ID 1397:0507 BEHRINGER International GmbH UMC202HD 192k

For the Corsair STRAFE Keyboard, the vendor ID would be 1b1c and the product ID 1b15

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