xiongyihui / notes

Notes
https://xiongyihui.github.io/notes/
3 stars 0 forks source link

Get the path of a USB device on Windows #27

Open xiongyihui opened 5 years ago

xiongyihui commented 5 years ago

We can run lsusb -t to get the path of a USB device on Linux, but not on Windows.

To get the path of a USB device or get USB device tree on Windows, install libusb python library (pip install libusb) and run a script:

#!/usr/bin/env python
#
# pip install libusb
#

from __future__ import print_function

import sys
import ctypes
import libusb as usb

def print_device(device_p, level):
    desc = usb.device_descriptor()
    usb.get_device_descriptor(device_p, ctypes.byref(desc))

    description = "{:04X}:{:04X}".format(desc.idVendor, desc.idProduct)

    bus = usb.get_bus_number(device_p)

    buffer = (ctypes.c_ubyte * 7)()
    pointer = ctypes.cast(ctypes.addressof(buffer), ctypes.POINTER(ctypes.c_ubyte))
    n = usb.get_port_numbers(device_p, pointer, 7)
    path = '-'.join([str(i) for i in buffer[:n]])

    address = usb.get_device_address(device_p)

    print("Bus {:d},\tDevice {:d},\tID {},\tPath {}".format(bus, address, description, path))

    return 0

def main(argv):
    r = usb.init(None)
    if r < 0:
        return r

    try:
        devs = ctypes.POINTER(ctypes.POINTER(usb.device))()
        cnt = usb.get_device_list(None, ctypes.byref(devs))
        if cnt < 0:
            return cnt

        i = 0
        while devs[i]:
            print_device(devs[i], 0)
            i += 1

        usb.free_device_list(devs, 1)
    finally:
        usb.exit(None)

    return 0

sys.exit(main(sys.argv) or 0)

The result is like:

Bus 1,  Device 20,      ID 0D28:0204,   Path 1-2
Bus 1,  Device 3,       ID 1286:204C,   Path 6
Bus 1,  Device 2,       ID 045E:091A,   Path 1
Bus 1,  Device 3,       ID 045E:07CD,   Path 1-4