- get name and device file path of usb device attached
- 1 Answer 1
- Code Example for Finding the Path of USB Devices in Linux
- Linux / libusb get usb device path
- How to find which device is attached to a USB-serial port in Linux using C?
- Identify what USB port is a device plugged into
- How to list USB mass storage devices programatically using libudev in Linux?
- Determine USB device file Path
- 2 Answers 2
get name and device file path of usb device attached
but it doesn’t show the device file path (i.e ttyUSB0). does it exist a command which does this? about dmesg and udevadm info they are too verbose. I would rather to have a simpler output, the best would be to append just the device file path to the output of lsusb, something like:
output without port: /: Bus 03.Port 1: Dev 1, Driver=xhci_hcd/4p, 480M |__ Port 1: Dev 4, If 0, Specific Class, Driver=ch341, 12M
Are you looking for the actual physical port, or the corresponding ttyUSB device path? That isn’t the «port», that’s the «Device file path»
I think dmesg -w is the easy way but check this answer for more options stackoverflow.com/questions/2530096/…
1 Answer 1
a lot of copy/paste brought me again here hoping that this would be helpful for others and also to improve my code
I used the almost perfect code from the answer in this question and added/removed some little stuff
#!/bin/bash for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do ( syspath="$" devname="$(udevadm info -q name -p $syspath)" [[ "$devname" == "bus/"* ]] || [[ "$devname" == "input/"* ]] || [[ "$devname" == "video0"* ]] || exit eval "$(udevadm info -q property --export -p $syspath)" [[ -z "$ID_SERIAL" ]] && exit busnum="$(udevadm info -a -p $(udevadm info -q path -n /dev/$devname) | awk -F "==" '/busnum/ ' | head -1)" devnum="$(udevadm info -a -p $(udevadm info -q path -n /dev/$devname) | awk -F "==" '/devnum/ ' | head -1)" bus_dev=$:$ lsusb="$(lsusb -s $bus_dev)" echo "$lsusb - /dev/$devname" ) done
Bus 003 Device 005: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter — /dev/ttyUSB0
NOTE: i don’t have any unix experience so if you would like to improve the code please do!
Code Example for Finding the Path of USB Devices in Linux
Execute the command before inserting the USB flash drive. Once inserted, the USB stick will display Kernel & Udev messages and indicate how the host sees it on the last line. To solve this issue, one option is to match devices based on specific criteria such as a child device existing with SUBSYSTEM == «block» and a parent device existing with SUBSYSTEM == «usb», DEVTYPE == «usb_device». Another solution is to create a symlink like /dev/thermoX by writing a udev-rule when attaching the device. An example program for the first solution can be found on Github.
Linux / libusb get usb device path
Starting from version 1.0.12, libusb has included a function called libusb_get_port_path(). However, in version 1.0.16, this function has been replaced with a new one called libusb_get_port_numbers(). With the latter, you can retrieve information about the bus topology.
In summary, an overview of the path structure in sysfs.
1-1.3:1.0 |_usb root hub - bus number - 1 |_ port number - 1 of root hub |_port number - 3 of intermediate hub |_current configuration number - 1 |_ current interface number - 0
Scan all USB devices across all buses until the required VID/PID is found, indicating the identification of the desired device.
Alternatively, you could simplify the process by creating a udev-rule that generates a symlink, such as /dev/thermoX, upon device attachment. Subsequently, all you need to do is access the appropriate /dev/thermoX.
Linux / libusb get usb device path, If i connect a usb-device with linux, i get a message in dmesg, here are a few examples for such a «device-path» with an usb temperature sensor (something like this): Directly to a usb port: [68448.099682] generic-usb 0003:0C45:7401.0056: input,hidraw1: USB HID v1.10 Keyboard [RDing TEMPer1V1.2] on usb-0000:00:12.0-1/input0 => 12.0-1 Code sample1-1.3:1.0|_usb root hub — bus number — 1|_ port number — 1 of root hub|_port number — 3 of intermediate hub|_current configuration number — 1Feedback
How to find which device is attached to a USB-serial port in Linux using C?
Symbolic links can be created specifically for your device by utilizing udev rules.
Consult your udev documentation to locate the directory /etc/udev/rules.d/ where you can place the rules with the naming convention -name.rules.
KERNEL=="ttyUSB*", ATTRS=="", MODE="0666", SYMLINK+="mydev"
In order to make your devices accessible at /dev/mydev, it is necessary to indicate the vendor id and/or product id of the device.
Utilize diverse parameters to generate distinctive symbolic links for your purpose, by referring to the udev manual.
I have adapted Alex Robinson’s code, eliminating the need for a global «except» statement.
import os from os.path import join def find_tty_usb(idVendor, idProduct): """find_tty_usb('067b', '2302') -> '/dev/ttyUSB0'""" # Note: if searching for a lot of pairs, it would be much faster to search # for the enitre lot at once instead of going over all the usb devices # each time. for dnbase in os.listdir('/sys/bus/usb/devices'): dn = join('/sys/bus/usb/devices', dnbase) if not os.path.exists(join(dn, 'idVendor')): continue idv = open(join(dn, 'idVendor')).read().strip() if idv != idVendor: continue idp = open(join(dn, 'idProduct')).read().strip() if idp != idProduct: continue for subdir in os.listdir(dn): if subdir.startswith(dnbase+':'): for subsubdir in os.listdir(join(dn, subdir)): if subsubdir.startswith('ttyUSB'): return join('/dev', subsubdir)
The provided code in Python can easily determine the /dev/ttyUSB number by specifying the vendor ID and product ID. It can be easily converted to C if needed. Alternatively, the output from hwinfo —usb can also be parsed using the following regular expression.
"\s\sVendor:\susb\s0x([0-9a-f]).*?\s\sDevice:\susb\s0x([0-9a-f]).*?\s\sDevice\sFile:\s/dev/ttyUSB(6+)"
import glob import os import re def find_usb_tty(vendor_id = None, product_id = None) : tty_devs = [] for dn in glob.glob('/sys/bus/usb/devices/*') : try : vid = int(open(os.path.join(dn, "idVendor" )).read().strip(), 16) pid = int(open(os.path.join(dn, "idProduct")).read().strip(), 16) if ((vendor_id is None) or (vid == vendor_id)) and ((product_id is None) or (pid == product_id)) : dns = glob.glob(os.path.join(dn, os.path.basename(dn) + "*")) for sdn in dns : for fn in glob.glob(os.path.join(sdn, "*")) : if re.search(r"\/ttyUSB6+$", fn) : #tty_devs.append("/dev" + os.path.basename(fn)) tty_devs.append(os.path.join("/dev", os.path.basename(fn))) pass pass pass pass except ( ValueError, TypeError, AttributeError, OSError, IOError ) : pass pass return tty_devs print find_usb_tty()
Retrieve USB information using pyudev with device name, An example output of this script would be:
Identify what USB port is a device plugged into
Obtain the device path of a device using udevadm , which examines the symlinks in /sys/ . Although this can be done manually, it is more convenient to use udevadm .
An instance would be when my system’s external USB hub is utilized to connect a USB stick.
$ udevadm info -q path -n /dev/sdh /devices/pci0000:00/0000:00:1d.0/usb3/3-1/3-1.1/3-1.1.3/3-1.1.3.2/3-1.1.3.2:1.0/host7/target7:0:0/7:0:0:0/block/sdh
By contrasting with the USB hierarchy, it is evident.
$ lsusb -t /: Bus 04.Port 1: Dev 1, Driver=xhci_hcd/2p, 5000M /: Bus 03.Port 1: Dev 1, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Driver=hub/8p, 480M |__ Port 1: Dev 26, If 0, Driver=hub/4p, 480M |__ Port 3: Dev 29, If 0, Driver=hub/4p, 480M |__ Port 2: Dev 31, If 0, Storage, Driver=usb-storage, 480M |__ Port 4: Dev 30, If 0, Storage, Driver=usb-storage, 480M .
The section labeled 3-1.1.3.2 outlines the route of bus 3, which includes passing through port 1 on the southbridge, then again on the motherboard, before reaching port 3 on the motherboard. Finally, the bus connects to port 2 on the external USB hub, where port 4 is dedicated for the SD card reader.
To obtain the desired outcome, you must extract the final port that aligns with the way your USB hub is linked.
It appears that /dev/disk/by-path includes symbolic links to nodes in /dev/sd* , making it a useful tool for discovering this information.
To obtain the physical addresses of all the /dev/sd* nodes, one can use the file /dev/disk/by-path/* command. It is simple to navigate through the results using grep.
Here’s an alternative approach to the usual solution, which involves supplying the name of a device to a command in order to obtain information about it.
Prior to inserting the USB flash drive, perform the following command:
Upon insertion, the USB stick will emit a verbose stream of Kernel & Udev messages and conclude with a final line indicating how the host perceives the device.
Linux — Bash script to detect when my USB is plugged in, For future reference, here’s how to run a bash script upon detection of a USB drive. Connect your device and run lsusb to retrieve the device’s info. You …
How to list USB mass storage devices programatically using libudev in Linux?
A viable option is to pair devices that meet the subsequent requirements:
- When the subsystem is «scsi» and the device type is «scsi_device».
- There is a device for children that has a SUBSYSTEM of «block».
- There is a device for children that has a «scsi_disk» subsystem.
- A device with a parent having the attributes SUBSYSTEM as «usb» and DEVTYPE as «usb_device» is present.
You can access a sample program (which is also accessible on Github).
#include #include static struct udev_device* get_child( struct udev* udev, struct udev_device* parent, const char* subsystem) < struct udev_device* child = NULL; struct udev_enumerate *enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_parent(enumerate, parent); udev_enumerate_add_match_subsystem(enumerate, subsystem); udev_enumerate_scan_devices(enumerate); struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate); struct udev_list_entry *entry; udev_list_entry_foreach(entry, devices) < const char *path = udev_list_entry_get_name(entry); child = udev_device_new_from_syspath(udev, path); break; >udev_enumerate_unref(enumerate); return child; > static void enumerate_usb_mass_storage(struct udev* udev) < struct udev_enumerate* enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, "scsi"); udev_enumerate_add_match_property(enumerate, "DEVTYPE", "scsi_device"); udev_enumerate_scan_devices(enumerate); struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate); struct udev_list_entry *entry; udev_list_entry_foreach(entry, devices) < const char* path = udev_list_entry_get_name(entry); struct udev_device* scsi = udev_device_new_from_syspath(udev, path); struct udev_device* block = get_child(udev, scsi, "block"); struct udev_device* scsi_disk = get_child(udev, scsi, "scsi_disk"); struct udev_device* usb = udev_device_get_parent_with_subsystem_devtype( scsi, "usb", "usb_device"); if (block && scsi_disk && usb) < printf("block = %s, usb = %s:%s, scsi = %s\n", udev_device_get_devnode(block), udev_device_get_sysattr_value(usb, "idVendor"), udev_device_get_sysattr_value(usb, "idProduct"), udev_device_get_sysattr_value(scsi, "vendor")); >if (block) udev_device_unref(block); if (scsi_disk) udev_device_unref(scsi_disk); udev_device_unref(scsi); > udev_enumerate_unref(enumerate); > int main()
The result for my external hard drive’s performance.
block = /dev/sdb, usb = 0bc2:ab20, scsi = Seagate
How to List Your Computer’s Devices From the Linux, sudo dnf install hdparm. 1. The mount Command. The mount command is used to mount filesystems. But issuing the command with no …
Determine USB device file Path
How can i get USB device file path correctly in Linux. I used command: find / -iname «usb» and got the result as below:
/dev/bus/usb /sys/bus/usb /sys/bus/usb/drivers/usb /sys/kernel/debug/usb
sh-3.2# ls /sys/bus/usb/devices/ 1-0:1.0 1-1:1.0 3-0:1.0 5-0:1.0 usb1 usb3 usb5 1-1 2-0:1.0 4-0:1.0 6-0:1.0 usb2 usb4 usb6
2:0:0:0 host0 host2 target2:0:0
So which device file is used for USB? How can i indentify it? I need to make a C program with USB device file. Further more, could you explain to me the number 1-1:1.0? What does it mean? Thank you.
I need to check informations which related to USB device. So i think i will send ioctl to USB device file and read the feedback data? Is this possible?
What do you mean with «read/write verification»? Is this for some specific device? Or are you trying to duplicate lsusb ?
2 Answers 2
So which device file is used for USB? How can i indentify it?
What you see behind /sys/ is mainly configuration/information about devices. /dev/bus/usb is what you are looking for. I think that the following article can help you
Is quite old, but still it can help you. (In the article they speak about /proc/bus/usb , today we have /dev/bus/usb )
Further more, could you explain to me the number 1-1:1.0? What does it mean?
Each field identify the connection point of your device. The first two field are mandatory:
- X is the USB bus of your motherboard where is connected the USB system.
- Y is the port in use on the bus system
So the USB device identified with the string 3-3 is the device connected on the port 3 of the bus 3.
If you connect an USB hub, you are extending the connection capability of a single USB port. The Linux kernel identify this situation by appending the Z field.
So, the USB device identified with the string 1-2.5 is the device connected on the port 5 of the hub connected on the port 2 of the bus 1.
USB specification allow you to connect in cascade more then one USB hub, so the Linux kernel continue to append the port in use on the different hubs. So, the USB device identified with the string 1-2.1.1 is the device connected on the port 1 of the hub connected on the port 1 of the hub connected to the port 2 of the bus 1.
A fast way to retrieve these information is to read the kernel messages (if you can).
$ dmesg | grep usb [. snip . ] [ 2.047950] usb 4-1: new full-speed USB device number 2 using ohci_hcd [ 2.202628] usb 4-1: New USB device found, idVendor=046d, idProduct=c318 [ 2.202638] usb 4-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0 [ 2.202643] usb 4-1: Product: Logitech Illuminated Keyboard [ 2.202648] usb 4-1: Manufacturer: Logitech [. snip . ]
Then, the last two fields of the pattern (after colon) identify an internal section of an USB device :
- A is the configuration number of the device
- B is the interface number of a configuration
So, the string 4-1:1.1 means: the interface 1, on configuration 1 that is connected on the port 1 of the bus 4.
You can retrieve these information with the command lsusb .