开发者

How can I detect when a flash drive is plugged in under Linux?

How can I detect when a flash drive is plugged in? I'm using a bare Debian ins开发者_运维知识库tallation, without any GUI and want to be notified in my Python script when a new flash drive appears... I know that D-BUS distributes such information, but i dont want to use D-BUS. Is there a more bare access to that information? Shouldn't that be available under /proc or /sys? How can I "connect" to that source?

Bye falstaff


All mayor Linux distros include udev, that allows you to write custom scripts on hardware events.


You can read uevents from kernel via a Netlink socket and look for events where "ACTION" is "add" (you can also watch if a partition from a device was mounted or unmounted, or if a device is being removed). That's as close to the source of events as one can get in user space. As far as I know, this is how udev detects inserted removable media.

But probably using D-Bus/HAL API via Python bingings will be much easier (no uevents data parsing, etc). Not sure why you are opposed to this. Since you are using Python, I suspect that resources are not really the issue.


If you are targetting an embedded device, then you can run mdev instead of udev. Then you can write mdev rules that are quite simple and triggers a script.

Of course you are not directly monitoring from your script, mdev is doing it, but you can launch any command. You can probably do the same thing with udev, but it always looked quite complicated to me.


When an USB device is plugged in syslog writes messages concerning this to /var/log/messages. The "dmesg" command shows this log. You can check near the end of the log to see which channel the device was attached to, it is usually /dev/sd(letter)(number) depending on the partitions and number of serial disks plugged into the system.


/proc/partitions shows all the partitions known to the kernel.


I did this using zenity in a script and udev with rule on rhel6 with:

KERNEL=="sd[b-d]", DRIVERS=="usb", ACTION=="add", RUN+="/path/to/script"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜