Added helper script to attach/detach USB devices

This commit is contained in:
Sheldon Lee 2023-10-02 06:14:59 +08:00
parent 4d299034e2
commit d6c22c0c45
5 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1 @@
../libvirt/attach-usb

View File

@ -0,0 +1,64 @@
#!/bin/bash
if [ "$(id -u)" -ne "0" ]; then
pkexec --keep-cwd sh -c "\
WAYLAND_DISPLAY=\"$WAYLAND_DISPLAY\"\
DISPLAY=\"$DISPLAY\"\
XDG_RUNTIME_DIR=\"$XDG_RUNTIME_DIR\"\
\"$0\""
exit 0
fi
run_as_user() {
if [ -z "$PKEXEC_UID" ]; then
USER_ID=1000
else
USER_ID="$PKEXEC_UID"
fi
username="$(id -nu "$USER_ID")"
cmd="$1"
echo "$(su "$username" sh -c "source \"/home/$username/.bash_profile\"; $cmd")"
}
csv="$(virsh list | tail --line=+3 | tr ' ' '\n' | uniq | grep -v -e "^[[:space:]]*$" | tr '\n' ',')"
vms="$(echo "$csv" | awk -F ',' -v n='3' '{
for (i = 1; i+1 <= NF; i++) {
printf "%s ", $i
if (i % n == 0) {
printf "\n"
}
}
}')"
if [ -z "$vms" ]; then
run_as_user "echo 'No VMs running' | menucmd -p 'Error'" &> /dev/null
exit 1
fi
vm="$(run_as_user "echo -e '$vms' | menucmd -p VM")"
vm_name=$(echo "$vm" | awk '{print $2}')
directory="./usb-devices"
item_list=""
for file in "$directory"/*; do
item_list="${item_list}${file}\n"
done
# strip last newline
end=${#item_list}-2
item_list=${item_list:0:end}
device="$(run_as_user "echo -e '$item_list' | menucmd")"
[ -z "$device" ] && exit 1
output=$(virsh attach-device "$vm_name" "$device" 2>&1) && echo "Attached $device to $vm_name"
if [ $? -ne 0 ]; then
virsh detach-device "$vm_name" "$device" &> /dev/null && echo "Detached $device from $vm_name"
if [ $? -ne 0 ]; then
attached_vm_name="$(echo "$output" | grep domain | rev | awk '{print $1}' | rev)"
virsh detach-device "$attached_vm_name" "$device" &> /dev/null && echo "Detached $device from $attached_vm_name"
virsh attach-device "$vm_name" "$device" &> /dev/null && echo "Attached $device to $vm_name"
fi
fi

View File

@ -0,0 +1,6 @@
<hostdev mode='subsystem' type='usb' managed='no'>
<source>
<vendor id='0x054c'/>
<product id='0x05c4'/>
</source>
</hostdev>

View File

@ -0,0 +1,6 @@
<hostdev mode='subsystem' type='usb' managed='no'>
<source>
<vendor id='0x046d'/>
<product id='0xc547'/>
</source>
</hostdev>

View File

@ -0,0 +1,6 @@
<hostdev mode='subsystem' type='usb' managed='no'>
<source>
<vendor id='0x4273'/>
<product id='0x7685'/>
</source>
</hostdev>