How to auto-detect a USB drive?

Mike Clarke jmc-freebsd2 at
Wed Mar 11 11:09:27 PDT 2009

On Wednesday 11 March 2009, Peter Steele wrote:

> Yeah, I guess my wording was a little vague. I know that the system
> automatically detects when a USB drive is inserted, and creates the
> appropriate entries under /dev. I want to follow this up with having
> the drive automatically mounted, and I'll then examine the USB drive
> for specific files I expect to be present, and possible run something
> that's installed on the disk, then unmount the disk. We want to use
> this approach to deploy our software on large clusters of machines
> that may not have an IP identity.

I do something like this. Here's the rules I have 
in /usr/local/etc/devd.conf

# Generic USB devices
attach 10 {
        match "device-name" "umass0";
        action "sleep 2; /root/bin/usbstick_attach > /dev/console";
# Cameras
attach 20 {
        match "device-name" "umass0";
	match  "vendor" "0x(07b4|04b0)";
        action "/bin/sleep 2 && mount -t msdosfs /dev/da0s1 /camera 
&& /root/bin/camcopy && umount /camera && echo ^G > /dev/console";

For most USB storage devices /root/bin/usbstick_attach parses the output 
of `camcontrol devlist` looking for entries like (da*,pass*) or 
(pass*,da*) and then it sets the permissions on the device to 660 and, 
for convenience, creates a link called usbstick in the dev directory 
pointing to the real device. This way the I can always 
mount /dev/usbstick on one of my own subdirectories without having to 
determine what device was created. I could have made the script mount 
the USB stick but if I have to make the effort to mount it myself I 
might be more likely to remember to unmount it afterwards.

The cameras are a special case since all I want to do is to check for 
new photos and copy them to my photo archive so if devd detects one of 
my cameras it mounts the camera with the higher priority "attach 20" 
rule which invokes /root/bin/camcopy to copy the photos before 
unmounting the camera and sounding the console bell to let me know I 
can unplug it.

The scripts are a bit primitive and get totally confused if I insert 
more than one USB storage device at a time so would need some 
refinement for general use but work OK for me as the only user on this 

Mike Clarke

More information about the freebsd-questions mailing list