# HOWTO: hotpluging usbstick automounting

## kENNy_

Hi,

I spend some time in automounting usb-sticks.

I'm using udev and hotpluging

for automounting create a bash script "usb-storage"

in the directory /etc/hotplug/usb/

```
#!/bin/sh

source /etc/profile

N=0

while [ 100 -gt $N ] ; do

  if [ -e /dev/sda1 ]; then

    N=100

  fi

  sleep 1

  N=$(( $N + 1 ))

done

/usr/bin/logger "mount -t vfat -o sync,umask=0 /dev/sda1 /mnt/usb"

mkdir -p /mnt/usb

mount -t vfat -o sync,umask=0 /dev/sda1 /mnt/usb
```

This script will try for 100 seconds to mount /dev/sda1 to /mnt/usb

make this script executable

```
chmod a+x /etc/hotplug/usb/usb-storage
```

next create an unmount script "usb-storage-remove" in the same directory /etc/hotplug/usb/

```
#!/bin/sh

/usr/bin/logger "umount /mnt/usb"

/bin/fuser -m -k /mnt/usb/

sleep 3

/bin/umount /mnt/usb
```

this script will kill all processes that access /mnt/usb after unplugging the usbstick

make this script executable

```
chmod a+x /etc/hotplug/usb/usb-storage-remove
```

test it, and watch your syslog...

have fun with this  :Smile: 

kENNy

----------

## servilvo

Hi, guys. 

I make it this script also. Try it. 

You have to put the next script "usb-storage"

in the directory /etc/hotplug/usb/

and make it executable chmod +x usb-storage

```
#!/bin/bash

#wait for logging messages

sleep 2

tail /var/log/messages -n11 > /tmp/usblog

DEVICE=`cat /tmp/usblog |grep sd | tail -n2 |head -n1 |cut -d ":" -f4 |cut -d " " -f2`

MOUNTDEV="/dev/$DEVICE"

NAMEDEV=`cat /tmp/usblog |grep Model |cut -d ":" -f 5|awk -F" " 'OFS="_"{$NF=""; print}'|sed -e "s/_$//g"`

MOUNTPOINT="/mnt/$NAMEDEV"

MOUNTOWNER=root

MOUNTGROUP=users

FESTIVALNAMEDEV=`cat /tmp/usblog |grep Model |cut -d ":" -f 5|awk -F" " '{$NF=""; print}'`

echo "Found a new U.S.B camera or disk which name is $FESTIVALNAMEDEV" | aoss festival --tts - &

#wait for the dev/sd* to be created

for I in 1 2 3 4 5 6 7 8 9 10 11 12 13

do

        if [ -e /dev/$DEVICE ]

      then 

         logger "`basename $0`: $I s to found $MOUNTDEV "

         break

   fi

   sleep 1

done

if [ -e /dev/$DEVICE ]

        then

                logger "`basename $0`: Mounting $NAMEDEV at $MOUNTPOINT "

        else

                logger "`basename $0`: ERROR $MOUNTDEV not found "

                exit

fi

aplay /usr/share/sounds/k3b_wait_media1.wav

#make fstab

FS=vfat

OPTIONS="users,uid=$MOUNTOWNER,gid=$MOUNTGROUP,sync,umask=007"

MOUNTCMD="$MOUNTDEV $MOUNTPOINT -t $FS -o $OPTIONS"

FSTABENTRY="$MOUNTDEV $MOUNTPOINT $FS noauto,$OPTIONS 0 0"

cat /etc/fstab | grep "$FSTABENTRY" > /dev/null || echo "$FSTABENTRY # $REMOVER" >> /etc/fstab

#automount usb-disk

mkdir $MOUNTPOINT

mount $MOUNTPOINT

#creating REMOVER

echo "#!/bin/bash" > $REMOVER

echo "echo \"Removing U.S.B camera or disk which name is $FESTIVALNAMEDEV \" | aoss festival --tts - & " >> $REMOVER

echo "rm -f /etc/fstab.usbremover" >> $REMOVER

echo "/bin/umount $MOUNTPOINT" >> $REMOVER

echo "/bin/cat /etc/fstab | /bin/grep -v \"$REMOVER\" > /etc/fstab.usbremover"  >> $REMOVER

echo "test -f /etc/fstab.old && rm /etc/fstab.old" >> $REMOVER

echo "mv /etc/fstab /etc/fstab.old " >> $REMOVER

echo "mv /etc/fstab.usbremover /etc/fstab " >> $REMOVER

echo "rmdir $MOUNTPOINT" >> $REMOVER

chmod +x $REMOVER
```

----------

## codergeek42

Not to sound condescending or anything, but isn't this what the HAL/dbus/{ivman,gnome-volume-manager} combo was meant to do but in a device-independent way?

----------

## Twink

 *codergeek42 wrote:*   

> Not to sound condescending or anything, but isn't this what the HAL/dbus/{ivman,gnome-volume-manager} combo was meant to do but in a device-independent way?

 

Actually last I checked ivman doesn't support usb sticks yet.

----------

## Naib

 *codergeek42 wrote:*   

> Not to sound condescending or anything, but isn't this what the HAL/dbus/{ivman,gnome-volume-manager} combo was meant to do but in a device-independent way?

 

and that is all well and good for GNOME2.8, what abt teh rest of us?

----------

## nevynxxx

 *Naib wrote:*   

>  *codergeek42 wrote:*   Not to sound condescending or anything, but isn't this what the HAL/dbus/{ivman,gnome-volume-manager} combo was meant to do but in a device-independent way? 
> 
> and that is all well and good for GNOME2.8, what abt teh rest of us?

 

Helping to get ivman working?

HAL depends only on DBUS, DBUS depends only on glib ( as far as I know, I run it on a comp without X-windows anyway) and ivman depends only on DBUS and HAL.

Its only the GVM that's gnome dependant. 

Ivman is young, if you want the usb stick functionality, contact ikke and help.

----------

## codergeek42

 *Twink wrote:*   

>  *codergeek42 wrote:*   Not to sound condescending or anything, but isn't this what the HAL/dbus/{ivman,gnome-volume-manager} combo was meant to do but in a device-independent way? 
> 
> Actually last I checked ivman doesn't support usb sticks yet.

 Aha. Thanks for clearing that up for me.  :Embarassed: 

----------

## Twink

my logs show that the usb device was inserted and detected however the usb-storage script is never run, any ideas?

----------

## lduperval

After tinkering a bit last nigh, I found out that the usb-storage script was never run. Instead (on 2.6, at least) it tries to run a script that has the name of the kernel module. In my case, it was "ub". So my /etc/hotplug/usb/ub script looks like this:

```

#!/bin/bash

sleep 2

DEVICE=`/usr/local/bin/usbid2ubdev $PRODUCT`

/usr/bin/logger "Device is $DEVICE"

MOUNTDEV="/dev/$DEVICE"

case "$PRODUCT" in

   4cb/16e/100) # Fuji camera

   echo "Mounting Fuji camera" | festival --tts - &

   MOUNTPOINT="/mnt/camera"

   ;;

esac

case "$PRODUCT" in

   781/7113/2033) # USB stick

   echo "Mounting Sandisk USB stick" | festival --tts - &

   MOUNTPOINT="/mnt/usbdrive"

   ;;

esac

MOUNTOWNER=root

MOUNTGROUP=users

#wait for the dev/sd* to be created

for I in 1 2 3 4 5 6 7 8 9 10 11 12 13

do

        if [ -e /dev/$DEVICE ]

      then

         logger "`basename $0`: $I s to found $MOUNTDEV "

         break

   fi

   sleep 1

done

if [ -e /dev/$DEVICE ]

        then

                logger "`basename $0`: Mounting $NAMEDEV at $MOUNTPOINT "

        else

                logger "`basename $0`: ERROR $MOUNTDEV not found "

                exit

fi

# aplay /usr/share/sounds/k3b_wait_media1.wav

#make fstab

FS=vfat

OPTIONS="users,uid=$MOUNTOWNER,gid=$MOUNTGROUP,sync,umask=007"

MOUNTCMD="$MOUNTDEV $MOUNTPOINT -t $FS -o $OPTIONS"

FSTABENTRY="$MOUNTDEV $MOUNTPOINT $FS noauto,$OPTIONS 0 0"

cat /etc/fstab | grep "$FSTABENTRY" > /dev/null || echo "$FSTABENTRY # $REMOVER" >> /etc/fstab

#automount usb-disk

mkdir $MOUNTPOINT

mount $MOUNTPOINT

#creating REMOVER

echo "#!/bin/bash" > $REMOVER

echo "echo \"Removing U.S.B camera or disk \" | festival --tts - & " >> $REMOVER

echo "rm -f /etc/fstab.usbremover" >> $REMOVER

echo "/bin/umount $MOUNTPOINT" >> $REMOVER

echo "/bin/cat /etc/fstab | /bin/grep -v \"$REMOVER\" > /etc/fstab.usbremover"  >> $REMOVER

echo "test -f /etc/fstab.old && rm /etc/fstab.old" >> $REMOVER

echo "mv /etc/fstab /etc/fstab.old " >> $REMOVER

echo "mv /etc/fstab.usbremover /etc/fstab " >> $REMOVER

echo "rmdir $MOUNTPOINT" >> $REMOVER

chmod +x $REMOVER

```

The usbid2ubdev script is a Tcl script (I don't do Perl):

```

#!/usr/bin/tclsh

if {[llength $argv] != 1} {

   puts stderr "Usage: $argv0 <device>"

   exit 1

}

if {![regexp {(.*)/(.*)/.*} [lindex $argv 0] -> vendorId productId]} {

   puts stderr "Device format should be xxxx/xxxx/xxxx"

   exit 2

}

proc padZero {num} {

   set pad [expr 4-[string length $num]]

   return [string repeat 0 $pad]$num

}

set vendorId [padZero $vendorId]

set productId [padZero $productId]

set deviceFile /proc/bus/usb/devices

set busInfo [split [exec grep "^T:" $deviceFile] \n]

set productInfo [split [exec grep "^P:" $deviceFile] \n]

for {set i 0} {$i < [llength $productInfo]} {incr i} {

   if {[string match "*Vendor=$vendorId ProdID=$productId*" [lindex $productInfo $i]]} {

      regexp {.*Port=(..)} [lindex $busInfo $i] -> port

      if {[string match "00" $port]} {

         puts "uba1"

      } elseif {[string match "01" $port]} {

         puts "ubb1"

      } else {

         puts stderr "Unknown port for $vendorId/$productId"

         exit 3

      }

      exit

   }

}

puts stderr "No match found"

```

----------

## Veneroso

This was working for me beautifully until gentoo-dev-sources-2.6.10-r4/6.  And if I use the old kernel, is still works.

I guess they changed something.  Looks like I have to look into alternatives, oh well.    :Rolling Eyes: 

The script is still called if the device is plugged in, but REMOVER is not executed if unplugged.  Also, hotplug isn't automounting it if it is plugged in at power on.

----------

## rasto

 *Veneroso wrote:*   

> This was working for me beautifully until gentoo-dev-sources-2.6.10-r4/6.  And if I use the old kernel, is still works.
> 
> I guess they changed something.  Looks like I have to look into alternatives, oh well.   
> 
> The script is still called if the device is plugged in, but REMOVER is not executed if unplugged.  Also, hotplug isn't automounting it if it is plugged in at power on.

 

Works for me...

2.6.10-gentoo-r4  sys-apps/hotplug-20040923  sys-fs/udev-045

I had to add this to recognize my usbstick and mount it to /mnt/usbstick

```

case "$PRODUCT" in

   ea0/2168/200) # USB stick

   echo "Mounting STF USB stick" | festival --tts - &

   MOUNTPOINT="/mnt/usbstick"

   FS=msdos

   ;;

esac

```

because i had to mount my usb stick with fs=msdos i added

```

if [ -z FS ] ; then

  FS=vfat

fi

```

also this was needed to fix creation of $REMOVER script

```

echo $'#!/bin/bash' > $REMOVER

```

so. now it looks like this.

```

#!/bin/bash

FS=

sleep 2

DEVICE=`/usr/local/bin/usbid2ubdev $PRODUCT`

/usr/bin/logger "Device is $DEVICE"

MOUNTDEV="/dev/$DEVICE"

case "$PRODUCT" in

   4cb/16e/100) # Fuji camera

   echo "Mounting Fuji camera" | festival --tts - &

   MOUNTPOINT="/mnt/camera"

   ;;

esac

case "$PRODUCT" in

   781/7113/2033) # USB stick

   echo "Mounting Sandisk USB stick" | festival --tts - &

   MOUNTPOINT="/mnt/usbdrive"

   ;;

esac

case "$PRODUCT" in

   ea0/2168/200) # USB stick

   echo "Mounting STF USB stick" | festival --tts - &

   MOUNTPOINT="/mnt/usbstick"

   FS=msdos

   ;;

esac

MOUNTOWNER=root

MOUNTGROUP=users

#wait for the dev/sd* to be created

for I in 1 2 3 4 5 6 7 8 9 10 11 12 13

do

        if [ -e /dev/$DEVICE ]

      then

         logger "`basename $0`: $I s to found $MOUNTDEV "

         break

   fi

   sleep 1

done

if [ -e /dev/$DEVICE ]

        then

                logger "`basename $0`: Mounting $NAMEDEV at $MOUNTPOINT "

        else

                logger "`basename $0`: ERROR $MOUNTDEV not found "

                exit

fi

# aplay /usr/share/sounds/k3b_wait_media1.wav

#make fstab

if [ -z FS ] ; then

  FS=vfat

fi

OPTIONS="users,uid=$MOUNTOWNER,gid=$MOUNTGROUP,sync,umask=007"

MOUNTCMD="$MOUNTDEV $MOUNTPOINT -t $FS -o $OPTIONS"

FSTABENTRY="$MOUNTDEV $MOUNTPOINT $FS noauto,$OPTIONS 0 0"

cat /etc/fstab | grep "$FSTABENTRY" > /dev/null || echo "$FSTABENTRY # $REMOVER"

 >> /etc/fstab

#automount usb-disk

mkdir $MOUNTPOINT

mount $MOUNTPOINT

#creating REMOVER

echo $'#!/bin/bash' > $REMOVER

echo "echo \"Removing U.S.B camera or disk \" | festival --tts - & " >> $REMOVER

echo "rm -f /etc/fstab.usbremover" >> $REMOVER

echo "/bin/umount $MOUNTPOINT" >> $REMOVER

echo "/bin/cat /etc/fstab | /bin/grep -v \"$REMOVER\" > /etc/fstab.usbremover"  

>> $REMOVER

echo "test -f /etc/fstab.old && rm /etc/fstab.old" >> $REMOVER

echo "mv /etc/fstab /etc/fstab.old " >> $REMOVER

echo "mv /etc/fstab.usbremover /etc/fstab " >> $REMOVER

echo "rmdir $MOUNTPOINT" >> $REMOVER

chmod +x $REMOVER

```

----------

## soya

 *lduperval wrote:*   

> After tinkering a bit last nigh, I found out that the usb-storage script was never run. Instead (on 2.6, at least) it tries to run a script that has the name of the kernel module. In my case, it was "ub". So my /etc/hotplug/usb/ub script looks like this:
> 
> ```
> 
> #!/bin/bash
> ...

 

For what i understand every time you plug a device using ub driver, ub script is executed. But when is the remover executed? Is it executed automatically? i don't understand how the remover works, so if someone wants to explain please. Another thing is, would ub-remove be executed after unplugging the device? I understand bash script so i understand the whole script, but don't know how remover works, when and why it is executed. i have another simply ub automoutn script and would like to run some commands when unplugging the device but as i have those questions i don't know how to do. thanks in advanced  :Smile: 

----------

## DrWoland

 *Twink wrote:*   

>  *codergeek42 wrote:*   Not to sound condescending or anything, but isn't this what the HAL/dbus/{ivman,gnome-volume-manager} combo was meant to do but in a device-independent way? 
> 
> Actually last I checked ivman doesn't support usb sticks yet.

 

 :Shocked:   Mine works fine.

----------

## Teh Penguin D00d

...correct me if I'm wrong...and I very well may be...

...but wouldn't pulling a mounted USB device without umounting it first cause nasty problems?  Or at the very least, "Device was not cleanly umounted" error messages?

And doesn't "killing all processes that access /mnt/usb" cause further issues?  I mean, if you have to kill the processes hard, who's to say they weren't in the middle of reading/writing the data?  The second case, of course, being far worse (as far as data integrity goes).

Wouldn't it make more sense to have a hotplug script, and then have a timer with a reasonable interval (say, 30 seconds?) that syncs, then umounts the drive?  Subsequent accesses to /mnt/usb could be handled as they were requested (I know rox can automount directories if they are in /etc/fstab, and requested, but not mounted...).

...or am I all wrong?

----------

## soya

i've done a very simply script that creates a kde icon after plugging the device, but i don't know how the remover works, my intention is to unmount the device with the kde icon and then the remover shoould act, removing the desktop icon. Is very simply but i'm stack wth teh remover, so hope someone can explain me how it works cause i've read something but can't get success

----------

## chidychi

 *soya wrote:*   

> i've done a very simply script that creates a kde icon after plugging the device, but i don't know how the remover works, my intention is to unmount the device with the kde icon and then the remover shoould act, removing the desktop icon. Is very simply but i'm stack wth teh remover, so hope someone can explain me how it works cause i've read something but can't get success

 

hey 

i'm just wondering if you figured it out..... 

and if not .. 

does the original remove script above work for you ?

----------

## mike_d

 *Teh Penguin D00d wrote:*   

> ...correct me if I'm wrong...and I very well may be...
> 
> ...but wouldn't pulling a mounted USB device without umounting it first cause nasty problems?  Or at the very least, "Device was not cleanly umounted" error messages?
> 
> And doesn't "killing all processes that access /mnt/usb" cause further issues?  I mean, if you have to kill the processes hard, who's to say they weren't in the middle of reading/writing the data?  The second case, of course, being far worse (as far as data integrity goes).
> ...

 

i also have this same question.  i just got a creative nomad muvo which is basically a usb flash drive.  i can manually mount it and copy files over to it, but the copying doesn't take place until the umount command is issued.  how does hotplug handle this?

mike

----------

## Teh Penguin D00d

 *mike_d wrote:*   

> 
> 
> i also have this same question.  i just got a creative nomad muvo which is basically a usb flash drive.  i can manually mount it and copy files over to it, but the copying doesn't take place until the umount command is issued.  how does hotplug handle this?
> 
> mike

 

Actually Mike, umount will call sync before umounting.  Sync finishes up all I/O requests, then returns.  After sync returns, umount does it's duty.

Try it for yourself.  Issue the copy command.  Execute sync.  So long as your copy command was decently long, it will pause for a while, then return to prompt.  Check mount to be sure that the device is still mounted.  It is.  Hard pull it.  You'll find the music still on the device.

The problem with the script, however, is that sync doesn't get called.  It's impossible to call sync once the drive is removed.  Well, I mean, you *can* call it.  But it's impossible for sync to do it's duty properly without the drive in place.  It can't sync to a drive that's not plugged in, after all.

----------

## mike_d

 *Teh Penguin D00d wrote:*   

> 
> 
> Actually Mike, umount will call sync before umounting.  Sync finishes up all I/O requests, then returns.  After sync returns, umount does it's duty.
> 
> Try it for yourself.  Issue the copy command.  Execute sync.  So long as your copy command was decently long, it will pause for a while, then return to prompt.  Check mount to be sure that the device is still mounted.  It is.  Hard pull it.  You'll find the music still on the device.
> ...

 

ah ha!  i never knew about the sync command.  i just assumed that umount did syncing on its own.  so basically, i need to execute two commands (1) cp to tell the stuff to go over to the flash drive and (2) sync to make sure it gets there.  

my goal is to make the use of the flashdrive wife proof.  so is there a away to tell gnome or kde to do a sync after a copy if the files are dragged and dropped (i.e. not close the 'copying files' dialog until the files are physically there)?  oviously i can write a script to do a cp and a sync actomatically from the command line, but  that would be for my use only.

----------

## Teh Penguin D00d

 *mike_d wrote:*   

> 
> 
> ah ha!  i never knew about the sync command.  i just assumed that umount did syncing on its own.  so basically, i need to execute two commands (1) cp to tell the stuff to go over to the flash drive and (2) sync to make sure it gets there.  
> 
> my goal is to make the use of the flashdrive wife proof.  so is there a away to tell gnome or kde to do a sync after a copy if the files are dragged and dropped (i.e. not close the 'copying files' dialog until the files are physically there)?  oviously i can write a script to do a cp and a sync actomatically from the command line, but  that would be for my use only.

 

And here's the problem with making something "wife proof."  The instant you create a brilliant modal window with no way of closing until the operation has completed, the wife creates a desire to move on (Or, dare I say, moves on to a different WM/DE  :Wink:  ).  Just like the "little happy globe of magic and wonder" I tell my girlfriend to click for Windows updates, your Window will get ignored, and the drive will be pulled.  Now, if you create a piece of hardware that somehow causes the USB drive to "lock" in, and become physically impossible to remove the flash drive until sync has completed, let me know.

You could always create a script that got mean and nasty with users if they pulled out the drive during a sync operation.  That's essentially Microsoft's approach.  Yell at users if they don't Eject the drive, or "Safely Remove Hardware."

I still think the idea of actively monitoring usage, and after a defined interval, umounting the drive is a good one.  And then, only remounting as the drive is requested.

...Perhaps I'll just have to take the aforementioned script into my own hands.  Perhaps when the kid goes to sleep tonight...

Keep me posted on that magical USB device locker, though.  :Wink: 

----------

## Teh Penguin D00d

 *mike_d wrote:*   

> 
> 
> ah ha!  i never knew about the sync command.  i just assumed that umount did syncing on its own.  so basically, i need to execute two commands (1) cp to tell the stuff to go over to the flash drive and (2) sync to make sure it gets there.  
> 
> my goal is to make the use of the flashdrive wife proof.  so is there a away to tell gnome or kde to do a sync after a copy if the files are dragged and dropped (i.e. not close the 'copying files' dialog until the files are physically there)?  oviously i can write a script to do a cp and a sync actomatically from the command line, but  that would be for my use only.

 

And here's the problem with making something "wife proof."  The instant you create a brilliant modal window with no way of closing until the operation has completed, the wife creates a desire to move on (Or, dare I say, moves on to a different WM/DE  :Wink:  ).  Just like the "little happy globe of magic and wonder" I tell my girlfriend to click for Windows updates, your Window will get ignored, and the drive will be pulled.  Now, if you create a piece of hardware that somehow causes the USB drive to "lock" in, and become physically impossible to remove the flash drive until sync has completed, let me know.

You could always create a script that got mean and nasty with users if they pulled out the drive during a sync operation.  That's essentially Microsoft's approach.  Yell at users if they don't Eject the drive, or "Safely Remove Hardware."

I still think the idea of actively monitoring usage, and after a defined interval, umounting the drive is a good one.  And then, only remounting as the drive is requested.

...Perhaps I'll just have to take the aforementioned script into my own hands.  Perhaps when the kid goes to sleep tonight...

Keep me posted on that magical USB device locker, though.  :Wink: 

----------

