Find which drive corresponds to which USB mass storage device in Linux

梦想与她 提交于 2019-11-30 20:55:58

I'm not sure in which kernel version this was implemented, but the /sys/block/* entries are symlinks to the devices.

In other words, /sys/block/sdb symlinks to a different directory, and its name contains the USB device ID.

$ file /sys/block/sdb
/sys/block/sdb: symbolic link to `../devices/pci0000:00/0000:00:02.1/usb1/1-1/1-1.1/1-1.1:1.0/host31/target31:0:0/31:0:0:0/block/sdb'
                                                  USB version and port here---^^^^^

The 1-1.1 is the interesting part, denoting usb1-port 1.device 1. When plugged into a hub, another level is added: 1-2.3.1, denoting usb1-port 2.port 3.device 1.

Pseudocode:

get partition name # e.g. /dev/sdb1
get disk name # that would be /dev/sdb
get your basename # sdb
see where /sys/block/$your_basename points to # e.g. ../devices/blah/blah/1-2.1/blah
get the longest substring matching "\d-\d+(.\d+)*"  # e.g. 1-2.1
that is the device id you want
/sys/bus/usb/devices/$device_id/ has all kinds of information about it
the ID corresponds to hardware USB ports

Working example script in bash.

Karter

I use the path:

/sys/bus/usb/drivers/usb-storage/4-1:1.0/host4/target4:0:0/4:0:0:0/block/sda

so you can see usb bus 4, port 1 is connected with a usb storage /dev/sda

genfoch01

Here is how I do it.

lsusb -v shows all the devices disks get an iserial number take note of them

 ls -l /dev/disk | grep [iserial] 

Everything in /dev/disk is a symlink so follow the symlink to see the device.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!