Search code examples
linuxusbpyusb

Un/bind a USB device via Python (preferably by PyUSB)


Is there a way with pyusb to unbind a USB device?

I know using the following bash the USB is unbound.

DEVICE=$(grep 064f /sys/bus/usb/devices/*/idVendor | tr '/' ' ' | awk '{ print $5 }')
/bin/bash -c "echo $DEVICE >/sys/bus/usb/drivers/usb/unbind"

But for various reasons I like to move away from bash and switch to Python, and ideally avoid maintaining my custom, complicated logic. So using a existing library makes sense to me.

Selected answer in stackoverflow.com#q54863367 suggests detach_kernel_driver to work for this purpose, but I don't see that happening on my environment; It does unmount the volume in the designated USB device (confirmed by watching the disk space on the USB disappears in lsblk's output) but I still see that OS detects the USB device.

$ ipython
In [7]: import usb
   ...: dev = usb.core.find(idVendor=0x064f, idProduct=0x03f3)
In [8]: dev.detach_kernel_driver(0)
$ watch lsusb
:
Bus 002 Device 043: ID 064f:03f3 WIBU-Systems AG CmStick/M (article no. 1011)

Environment

Linux (At the time of writing, Ubuntu 16.04 (I know EoLed) or 18.04. But environment shouldn't be a limiting factor. Open for available solutions regardless the version.


UPDATE: My usecase requires mimicing removal of USB device. We've been happy with the operation typically called as un/bind, and also happy with the bash solution to realize un/bind.


Solution

  • Thought I'd close OP but coudln't choose an appripriate reason so answer by myself instead.

    As I concluded myself with a help from the maintainer in pyusb#399 I found I was misunderstood. Using detach_kernel_driver as suggested in stackoverflow.com#q54863367 worked for my purpose as well.