#!/bin/bash # make sure we have the required udev variables if [ -z "$BUSNUM" -o -z "$DEVNUM" -o -z "$DEVPATH" ]; then exit 1 fi declare -rg _vboxdir="/usr/lib/virtualbox" declare -rg _vboxmanage="${_vboxdir}/VBoxManage" declare -rg _vboxruntime="${_vboxdir}/VirtualBox" declare -r user="$(ps aux | grep "$_vboxruntime" | grep -v grep | awk '{print $1}')" if [ -z "$user" ] || ! id "$user" &> /dev/null; then # No user session with virtualbox is running, exit silently exit 0 fi export VBOX_IPC_SOCKETID="$user" # find UUID of running VM vmuuid="$("$_vboxmanage" list runningvms | awk '{print $NF}' | tr -d '{}')" if [ -z "$vmuuid" ]; then logger "Failed to find running VirtualBox instance of '$user'." exit 1 fi devname="/dev/vboxusb/$BUSNUM/$DEVNUM" for tts in 1 1 1 1 1 2 3 5 STOP; do if [ "x$tts" = "xSTOP" ]; then logger "$0: Could not find '$devname' as expected..." exit 1 fi [ -e "$devname" ] && break logger "waiting for $devname..." sleep $tts done usbaddress="$("$_vboxmanage" list usbhost | grep "$DEVPATH" | awk '$1 = /Address:/ {print $2}')" logger "Trying to attach '$usbaddress' to '$vmuuid'..." for tries in 1 2 3 STOP; do if [ "$tries" = "STOP" ]; then logger "$0: Failed after 3 tries!" exit 1 fi if "$_vboxmanage" controlvm "$vmuuid" usbattach "$usbaddress"; then exit 0 fi sleep 1 done