如何從 lsusb 輸出或透過裝置路徑取得裝置檔案名稱

如何從 lsusb 輸出或透過裝置路徑取得裝置檔案名稱

相關問題:USB 連接/斷開通知

當設備插入/拔出時,我會收到即時通知,這很棒。但為了使其(幾乎)完美,我還想獲取設備文件名,例如/dev/ttyUSB0,甚至更好的是它的所有符號鏈接。

但是,我找不到如何從udev、 或 從lsusb或其他方式獲取此資訊。我擁有的設備的唯一 ID 是設備路徑,例如/devices/pci0000:00/0000:00:1d.0/usb5/5-1.如何從中取得設備檔案名稱?

答案1

假設我正在嘗試為我的 UVC 相機找到設備,lsusb 會給我:

Bus 001 Device 004: ID 1e4e:0102 Cubeternet GL-UPC822 UVC WebCam

然後是裝置檔案名稱/dev/bus/usb/001/004(第一個元件是匯流排 ID,接下來是裝置 ID)。

答案2

我剛剛為此構建了一個腳本,它並不漂亮,但對我有用。

我使用以下配置在 Arch Linux 上測試了此腳本:

$ uname -a
Linux 4.4.13-1-lts #1 SMP Wed Jun 8 16:44:31 CEST 2016 x86_64 GNU/Linux

我的設備名稱/dev/sdb與您的完全不同,我希望它也適合您。

另請注意,該腳本依賴程式usbutilsusb-devices,我相信它預設安裝在所有 Linux 上,但我可能是錯的。

腳本usbname

#!/usr/bin/bash

# Input should be a single line from lsusb output:
DATA=$1

# Read the bus number:
BUS=`echo $DATA | grep -Po 'Bus 0*\K[1-9]+'`

# Read the device number:
DEV=`echo $DATA | grep -Po 'Device 0*\K[1-9]+'`

FOUND=false
USB_Serial=""

# Search for the serial number of the PenDrive:
while read line
do
  if [ $FOUND == true ]; then
    USB_Serial=`echo "$line" | grep -Po 'SerialNumber=\K.*'`
    if [ "$USB_Serial" != "" ]; then
      break;
    fi
  fi

  if [ "`echo "$line" | grep -e "Bus=0*$BUS.*Dev#= *$DEV"`" != "" ]; then
    FOUND=true
  fi
done <<< "$(usb-devices)"

# Get the base name of the block device, e.g.: "sdx"
BASENAME=`file /dev/disk/by-id/* | grep -v 'part' | grep -Po "$USB_Serial.*/\K[^/]+$"`

# Build the full address, e.g.: "/dev/sdx"
NAME="/dev/$BASENAME"

# Output the address:
echo $NAME

用法:

$ ./usbname "$(lsusb | grep '<my_usb_label_or_id>')"
/dev/sdb

答案3

我使用這個小 bash 函數

getdevice() {
    idV=${1%:*}
    idP=${1#*:}
    for path in `find /sys/ -name idVendor | rev | cut -d/ -f 2- | rev`; do
        if grep -q $idV $path/idVendor; then
            if grep -q $idP $path/idProduct; then
                find $path -name 'device' | rev | cut -d / -f 2 | rev
            fi
        fi
    done
}

例子

# lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 8087:0a2b Intel Corp.
Bus 001 Device 012: ID 0bda:2832 Realtek Semiconductor Corp. RTL2832U DVB-T
Bus 001 Device 053: ID 051d:0002 American Power Conversion Uninterruptible Power Supply
Bus 001 Device 051: ID 1cf1:0030 Dresden Elektronik
Bus 001 Device 006: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter
Bus 001 Device 004: ID 05e3:0606 Genesys Logic, Inc. USB 2.0 Hub / D-Link DUB-H4 USB 2.0 Hub
Bus 001 Device 003: ID 0658:0200 Sigma Designs, Inc. Aeotec Z-Stick Gen5 (ZW090) - UZB
Bus 001 Device 002: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

以及相應的設備

# getdevice 051d:0002
hiddev0
hidraw0

# getdevice 1a86:7523
ttyUSB0

# getdevice 0658:0200
ttyACM1

相關內容