Linux Bash 脚本来检测我的 USB 何时插入,然后将它与目录同步

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4189383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:58:51  来源:igfitidea点击:

Bash script to detect when my USB is plugged in and to then sync it with a Directory

linuxbashusbudev

提问by

Is there a Bash script and/or daemon that I can write that will detect a specific USB drive and then sync that drive with a directory?

是否有我可以编写的 Bash 脚本和/或守护程序来检测特定的 USB 驱动器,然后将该驱动器与目录同步?

回答by Piotr Findeisen

I didn't do it myself, but you can try udevrules like this:

我不是自己做的,但你可以尝试这样的udev规则:

# Hitachi SimpleDrive mini, model HTS545050B9A300 (500 GB USB HDD)
SUBSYSTEM=="block", ATTR{size}=="976768002", ATTRS{product}=="SimpleDrive mini", ATTRS{serial}=="2512009121920487", ACTION=="add", RUN+="/lib/udev/local.usb.hdd.sh add $devpath"

Place it in /etc/udev/rules.d/90-local.rulesor similar place, certainly dependable on your OS.

把它放在/etc/udev/rules.d/90-local.rules或类似的地方,当然取决于你的操作系统。

回答by VKolev

Here is an examplepython deamon that you could use for the listening part, then copying the files to your directory shouldn't be a problem.

这是一个示例python deamon,您可以将其用于侦听部分,然后将文件复制到您的目录应该不成问题。

回答by slybloty

For future reference, here's how to run a bash script upon detection of a USB drive.

为了将来参考,这里是如何在检测到 USB 驱动器时运行 bash 脚本。

Connect your device and run lsusbto retrieve the device's info. You should see something similar to this:

连接您的设备并运行lsusb以检索设备的信息。您应该会看到类似的内容:

$ lsusb
Bus 002 Device 039: ID 0bc2:2100 Seagate RSS LLC
$ lsusb
Bus 002 Device 039: ID 0bc2:2100 Seagate RSS LLC

In this case, the vendor ID of the device is 0bc2 and the product ID is 2100.

在这种情况下,设备的供应商 ID 为 0bc2,产品 ID 为 2100。

Now you can create your UDEV rule using a text editor of your choice.

现在您可以使用您选择的文本编辑器创建您的 UDEV 规则。

$sudo vi /etc/udev/rules.d/85-my_usb_device_rule.rules

$sudo vi /etc/udev/rules.d/85-my_usb_device_rule.rules

And add this:

并添加这个:

ACTION=="add", SUBSYSTEM=="usb", SYSFS{idVendor}=="0bc2", SYSFS{idProduct}=="2100", RUN+="/home/myhome/my_script"

ACTION=="add", SUBSYSTEM=="usb", SYSFS{idVendor}=="0bc2", SYSFS{idProduct}=="2100", RUN+="/home/myhome/my_script"

/home/myhome/my_scriptis the path to your script which it would do whatever you want.

/home/myhome/my_script是你的脚本的路径,它可以做任何你想做的事。

To make sure the detection script will execute right away, run this command to reload the UDEV rules:

要确保检测脚本立即执行,请运行以下命令以重新加载 UDEV 规则:

$sudo udevadm control --reload-rules

$sudo udevadm control --reload-rules

This was tested on Fedora 14.

这是在 Fedora 14 上测试的。