Linux基于usb端口执行脚本



你好,我正在开发安装在嵌入式系统上的debian系统。电脑有3个usb端口,我们称之为A、B、C。我想基于usb端口执行不同的脚本。我该如何实现这一点?

我发现了很多关于udev规则的文章,我有下面的规则,如果我连接了usb,它就可以工作。

ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd[a-z]1", SYMLINK+="usb_to_check", RUN+="/usr/local/bin/check-usb1.sh"

如果我连接了一个设备,比如说usb a,我如何才能将此规则扩展到工作??

lsusb输出USB总线和连接设备的USB端口。在输出中,一些USB根集线器是内部USB集线器,还连接了蓝牙和网络摄像头等,请参阅https://unix.stackexchange.com/questions/144029/command-to-determine-ports-of-a-device-like-dev-tty-usb0

你应该弄清楚你的外部端口连接在哪条USB总线上。在我的计算机上,所有外部USB端口都链接到Bus 01

要执行此操作,请检查lsusb -t的输出,然后连接usb设备并再次检查lsusb -t的输出。然后你就知道你的三个外部usb端口在你的设备内部usb结构树中有什么地址:

内部USB端口:

/:  Bus 04.Port 1: Dev 1, Class=root_hub, Driver=ohci_hcd/5p, 12M
/:  Bus 03.Port 1: Dev 1, Class=root_hub, Driver=ohci_hcd/5p, 12M
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/5p, 480M
|__ Port 1: Dev 64, If 0, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M
|__ Port 1: Dev 64, If 1, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M

外部USB端口:

/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/5p, 480M
|__ Port 3: Dev 116, If 0, Class='bInterfaceClass 0xe0 not yet handled', Driver=rndis_host, 480M
|__ Port 3: Dev 116, If 1, Class=data, Driver=rndis_host, 480M

USB记忆棒连接到外部端口#2

/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/5p, 480M
|__ Port 2: Dev 119, If 0, Class=stor., Driver=usb-storage, 480M
|__ Port 3: Dev 116, If 0, Class='bInterfaceClass 0xe0 not yet handled', Driver=rndis_host, 480M
|__ Port 3: Dev 116, If 1, Class=data, Driver=rndis_host, 480M

在这个过程之后,你的外部USB端口的"地址">

dmesg中,连接的USB设备总是显示一条包含USB总线和端口号的线路:

[186067.360139] usb 1-1: new high-speed USB device number 123 using ehci_hcd是总线001端口001

[186067.360139] usb 1-2: new high-speed USB device number 123 using ehci_hcd是总线001端口002

[186067.360139] usb 1-3: new high-speed USB device number 123 using ehci_hcd是总线001端口003

在您的脚本中,您可以使用命令dmesg | grep "usb 1" | tail -1来grep这一行(tail-1 grep最后一次出现,请参阅http://www.stackoverflow.com/questions/24014194/how-to-grep-the-last-occurence-of-the-line-pattern)

您可以使用命令直接获取端口号

dmesg | grep -o -P 'usb 1.{0,3}' | tail -1 | head -c 7 | tail -c 1(如果所有外部端口都在Bus 001上)

(比赛前和比赛后的Grep字符?,http://www.unix.com/unix-for-dummies-questions-and-answers/28542-how-do-i-get-nth-character-string.html)

因此,有了这个,你就可以获得连接最新USB设备(你的设备)的USB端口号,这可以在你的udev脚本(if ...)中使用


您还可以在/dev/bus/usb/文件系统中找到USB总线树结构,即总线01端口1是/dev/bus/usb/001/001

参见http://www.linuxnix.com/find-usb-device-details-in-linuxunix-using-lsusb-command/

有更好的解决方案。可以使用udev基于棒的vendorIDproductID指定特定的/dev/x设备节点,请参阅https://askubuntu.com/questions/127695/force-specific-letter-for-usb-drive-in-dev-sd(x是任意名称)

使用此固定设备节点,您可以使用udevadm查询设备连接的USB端口

udevadm info --query=all --attribute-walk --name/dev/x

并从中grep USB端口号(请参阅其他答案…)