Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
USB Stick Automounter
View unanswered posts
View posts from last 24 hours

Goto page 1, 2, 3  Next  
Reply to topic    Gentoo Forums Forum Index Kernel & Hardware
View previous topic :: View next topic  
Author Message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Wed Dec 10, 2003 10:55 pm    Post subject: USB Stick Automounter Reply with quote

Hey all,


Because I wasn't able to find a automounting program for an simple USB stick I created one myself in a simple script.

I think the code below says it all.

Code:

#!/bin/sh
# Shell script made by Eric Oud Ammerveld
# Dislclaimer : Should this script f*ck up your computer,
#               I'm not the one to blame.
#
#
                                                                                                     
# Run for ever
while [ 1 ]
do
                                                                                                     
#--------- CONFIG ------------#
#location of the stick (usually sd[x])
usbstick="sdb"
                                                                                                     
usbpart1="/dev/"$usbstick"1" #Partition 1 on the stick
mntpth1="/mnt/usb1" #Mount Path 1
fs1="vfat" #File system 1
                                                                                                     
usbpart2="/dev/"$usbstick"5" #Partition 2 on the stick (located in extended partition)
mntpth2="/mnt/usb2" #Mount Path 2
fs2="vfat" #File system 2 (vfat=dos/fat16/fat32 , ntfs ;type man mount for more fs)
#--------- CONFIG END---------#
                                                                                                     
mntd="`/bin/mount | /bin/grep -c $usbstick`"
checkstick="`/bin/ls /dev |/bin/grep -c $usbstick`"
                                                                                                     
#/bin/echo "Amount of sticks :$checkstick" # A few debug rules
#/bin/echo "Mounted sticks :$mntd"
#/bin/echo "Partition 1: "$usbpart1
#/bin/echo "Partition 2: "$usbpart2
                                                                                                     
if [ $mntd == 0 ] # If the stick is not mounted...
then
  if [ $checkstick == 4 ] # Though the stick is detected...
  then
    /bin/wall "USB Stick found! Mounting"
    /bin/mount $usbpart1 $mntpth1 -t $fs1 # Mount it
    /bin/mount $usbpart2 $mntpth2 -t $fs2 # Mount it
  fi
else
  if [ $checkstick == 0 ] # If the stick isn't present...
  then
    /bin/wall "USB Stick removed! Unmounting"
    /bin/umount -f $mntpth1 > /dev/null # Unmount it
    /bin/umount -f $mntpth2 > /dev/null # Unmount it
  fi
fi
/bin/sleep 5 # Short time-out to reduce the load
done


Please do inform me if you have a better way or if you have
adapted the script.

Regards,

-=@@D=-
Back to top
View user's profile Send private message
taskara
Advocate
Advocate


Joined: 10 Apr 2002
Posts: 3763
Location: Australia

PostPosted: Wed Dec 10, 2003 11:45 pm    Post subject: Reply with quote

what are u calling your script?

also r u using usb hotplug? it's very handy if ur not..
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Thu Dec 11, 2003 10:02 am    Post subject: USBSTICKD Reply with quote

taskara wrote:
what are u calling your script?

also r u using usb hotplug? it's very handy if ur not..


I called my script "usbstickd" (USB Stick Daemon)
I enabled hotplug and of course generic SCSI stuph in my kernel(/dev/sd typically indicates a SCSI device which your USB stick needs to emulate it's presence).

(Tested with kernel 2.6.0-test 11)

use "dmesg" to check weather the kernel detects your USB stick.
(a sd[x] device will be found)
Back to top
View user's profile Send private message
oisch
Tux's lil' helper
Tux's lil' helper


Joined: 17 Jul 2002
Posts: 130

PostPosted: Thu Dec 11, 2003 12:11 pm    Post subject: Reply with quote

I enabled supermount in the kernel and used the following entry for automounting:
Code:
none                   /mnt/usbstick   supermount      dev=/dev/sda1   0 0

This works very good, but I'm not sure if the data integrity is ensured. When I write on my usb stick I have a delay of some seconds and unmounting is denied.
So if I just unplug the usb stick it may be that not all data has been transfered.
So I prefer so old mount / umount way to acces the usb stick.

Your script seems to unmount the stick when it's been removed. Do you think it is save to remove it while it is mounted?
Back to top
View user's profile Send private message
taskara
Advocate
Advocate


Joined: 10 Apr 2002
Posts: 3763
Location: Australia

PostPosted: Thu Dec 11, 2003 12:45 pm    Post subject: Reply with quote

I also mount manually.. and I don't think it's a good idea to unplug it b4 umounting has finished.. usb devices have delay write, so ur data may be corrupt..
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Fri Dec 12, 2003 10:04 am    Post subject: Reply with quote

oisch wrote:
I enabled supermount in the kernel and used the following entry for automounting:
Code:
none                   /mnt/usbstick   supermount      dev=/dev/sda1   0 0

This works very good, but I'm not sure if the data integrity is ensured. When I write on my usb stick I have a delay of some seconds and unmounting is denied.
So if I just unplug the usb stick it may be that not all data has been transfered.
So I prefer so old mount / umount way to acces the usb stick.

Your script seems to unmount the stick when it's been removed. Do you think it is save to remove it while it is mounted?


Technically it's not very safe to remove a mounted device, especially not when it is in use.
It's just a thing you should keep in mind and try to avoid while using the USB stick.
If the device isn't present anymore the daemon will detect within 5 seconds and force a unmount.

I don't know what exactly will happen when you unplug the stick while writing to it but even
if it stays mounted and the write buffer is still filled I think the data in the write buffer will be blanked (output /dev/null) as soon as module that contols the buffer detects that it cannot write to the device.

If the buffer module is activated and deactivated controlled by the mount of the device the buffer probably will be wiped out. :(

If the buffer module is a kernel module it's also possible that the buffer will be wiped clean (for security and robustness reasons)
Because if you would insert another USB Stick while the buffer is still filled it would probably lead to even more complications.
The way linux is programmed I think every programmer would like to avoid complications like that because every situation possible should bel programmed otherwise.

I think in both cases, the worst thing you can do is unplug your stick while writing to it.

I wonder how supermount handles the mount and unmount story when the buffer is filled and the stick is unplugged. :?:
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Fri Dec 12, 2003 11:04 am    Post subject: Reply with quote

taskara wrote:
I also mount manually.. and I don't think it's a good idea to unplug it b4 umounting has finished.. usb devices have delay write, so ur data may be corrupt..


I think that in both cases the buffer will be dropped so a corrupt file(system) would be inevitable in both cases. :roll:
Back to top
View user's profile Send private message
taskara
Advocate
Advocate


Joined: 10 Apr 2002
Posts: 3763
Location: Australia

PostPosted: Fri Dec 12, 2003 11:49 am    Post subject: Reply with quote

genotix wrote:
taskara wrote:
I also mount manually.. and I don't think it's a good idea to unplug it b4 umounting has finished.. usb devices have delay write, so ur data may be corrupt..


I think that in both cases the buffer will be dropped so a corrupt file(system) would be inevitable in both cases. :roll:


which two cases?
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Fri Dec 12, 2003 1:08 pm    Post subject: Reply with quote

taskara wrote:
genotix wrote:
taskara wrote:
I also mount manually.. and I don't think it's a good idea to unplug it b4 umounting has finished.. usb devices have delay write, so ur data may be corrupt..


I think that in both cases the buffer will be dropped so a corrupt file(system) would be inevitable in both cases. :roll:


which two cases?


Case 1 : supermount
Case 2 : usbstickd
Back to top
View user's profile Send private message
Mankane
n00b
n00b


Joined: 22 Mar 2003
Posts: 27

PostPosted: Sat Dec 13, 2003 6:32 am    Post subject: Reply with quote

oisch wrote:
I enabled supermount in the kernel and used the following entry for automounting:
Code:
none                   /mnt/usbstick   supermount      dev=/dev/sda1   0 0

This works very good, but I'm not sure if the data integrity is ensured. When I write on my usb stick I have a delay of some seconds and unmounting is denied.
So if I just unplug the usb stick it may be that not all data has been transfered.
So I prefer so old mount / umount way to acces the usb stick.

Your script seems to unmount the stick when it's been removed. Do you think it is save to remove it while it is mounted?


If you're doing any kind of unplugging before umounting, you should really be specifying the sync option. By not doing so you're risking loss of data and filesystem corruption. See 'man mount' for more info about the sync option.

That said, Windows warns you about stopping the device if you just unplug and manually umounting is along those same lines (windows also disables asynchronous transfers for jump drives as well in 2000 and xp, but still recommends stopping the device).
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Sat Dec 13, 2003 8:21 am    Post subject: Reply with quote

Mankane wrote:
oisch wrote:
I enabled supermount in the kernel and used the following entry for automounting:
Code:
none                   /mnt/usbstick   supermount      dev=/dev/sda1   0 0

This works very good, but I'm not sure if the data integrity is ensured. When I write on my usb stick I have a delay of some seconds and unmounting is denied.
So if I just unplug the usb stick it may be that not all data has been transfered.
So I prefer so old mount / umount way to acces the usb stick.

Your script seems to unmount the stick when it's been removed. Do you think it is save to remove it while it is mounted?


If you're doing any kind of unplugging before umounting, you should really be specifying the sync option. By not doing so you're risking loss of data and filesystem corruption. See 'man mount' for more info about the sync option.

That said, Windows warns you about stopping the device if you just unplug and manually umounting is along those same lines (windows also disables asynchronous transfers for jump drives as well in 2000 and xp, but still recommends stopping the device).


In one of the first topics supermount was also mentioned.
Unfortunately I have not found the emerge package for it.
emerge -s supermount results in no download options.

I was thinking about a method that writes the table of contents later to the stick but this should be programmed on a lower level.
The script above was just something I needed but didn't find in any packages.

My method works good for me only you should keep in mind buffering is used.

Could you help me out with the sync option?
Back to top
View user's profile Send private message
oisch
Tux's lil' helper
Tux's lil' helper


Joined: 17 Jul 2002
Posts: 130

PostPosted: Sat Dec 13, 2003 6:37 pm    Post subject: Reply with quote

Quote:
In one of the first topics supermount was also mentioned.
Unfortunately I have not found the emerge package for it.
emerge -s supermount results in no download options.


You need to patch your kernel to use supermount. gentoo-dev-sources already have this patch applied automatically. You should find the supermount option under Filesystems.

I use supermount for CD and Floppy mounting/unmounting.
Using the SYNC option for an usb stick really slows down writing, so that ain't an option, too. I'll stick to manual mount/unmounting, as it really isn't so much work.
Back to top
View user's profile Send private message
tuxlover
Apprentice
Apprentice


Joined: 21 Oct 2003
Posts: 297
Location: weltweit

PostPosted: Sat Dec 13, 2003 7:34 pm    Post subject: Reply with quote

oisch wrote:
I enabled supermount in the kernel and used the following entry for automounting:
Code:
none                   /mnt/usbstick   supermount      dev=/dev/sda1   0 0

This works very good, but I'm not sure if the data integrity is ensured.

As far as I know, supermount is supposed to handle just that - data integrity for removable media. From the supermount homepage:
"Supermount detects when you have finished activity on the subfs, and will flush all buffers to the disk before completing the operation. So, if you copy a file onto a supermounted floppy disk, the data will all be written to disk before the "cp" command finishes. When the command does complete, it will be safe to remove the disk."

Now I'm confused... What is supermount-ng? Is it different from supermount...?
Back to top
View user's profile Send private message
bedouin
n00b
n00b


Joined: 19 Oct 2003
Posts: 4

PostPosted: Mon Dec 15, 2003 6:24 pm    Post subject: Reply with quote

#1: Data integrity
If you can live with really poor write performance then mount the device in synchronous mode:
Code:

/dev/sda1   /mnt/usb-storage      auto      sync,dirsync   0   0

That way data gets written to the stick immediately, your application will be blocked until the write is complete. Of course writing is quite slow, so don't use that for swap :wink:
On the other hand, there will be no stale buffers. It's OK to unplug whenever the stick is not being accessed.

The above line is the basis for everything described below.

#2: Automounting
I don't know about supermount (never used it) but for my stick I'm using the standard hotplug infrastructure: enable hotplug in the kernel and emerge sys-apps/hotplug. This will (among other things) give you scripts in /etc/hotplug.d and /etc/hotplug/<SUBSYSTEM> (for example: /etc/hotplug/usb)

The scripts in /etc/hotplug.d (usually just "default") will switch incoming hotplug events by subsystem, you'd modify that if have a new kind of hotplug system. Not interesting.

Now in /etc/hotplug/usb you would place scripts with the name of a kernel module, e.g. /etc/hotplug/usb/usb-storage, looking like this:

Code:

#!/bin/bash

# NOTE: to make this work, you *MUST* use the options "sync" and "dirsync" in your /etc/fstab !!!
#       otherwise you *WILL* lose data

#create a script to undo our actions upon removal
echo "#!/bin/bash" > $REMOVER
chmod a+x $REMOVER

if [ "$INTERFACE" = "8/6/80" ]; then
  mount /mnt/usb-storage
  echo "umount -f /mnt/usb-storage" >> $REMOVER
fi


This script will be executed when and if
* there is a USB hotplug event
* this event has already caused the module usb-storage.o to be loaded

The environment variables $REMOVER, $INTERFACE and $PRODUCT (and some others I don't remember) will be set by the hotplug infrastructure. The check for $INTERFACE=8/60/80 ensures that we are really dealing with a storage device. If your storage device needs special handling you might also check $PRODUCT (check your hotplug logs to find out your stick's product ID).

The file $REMOVER (if it exists) will be executed upon removal of the exact device it was created for.

The above script is all fine and dandy if you only have one user, one stick, and one location to mount it on. And else :?:

Well, try the following script for /etc/hotplug/usb/usb-storage, which is an extension of the previous example:
Code:

#!/bin/bash

# NOTE: to make this work, you *MUST* use the options "sync" and "dirsync" in your /etc/fstab !!!
#       otherwise you *WILL* lose data

#create a script to undo our actions upon removal
echo "#!/bin/bash" > $REMOVER
chmod a+x $REMOVER

# INTERFACE=8/6/80 means "mass storage device"
if [ "$INTERFACE" = "8/6/80" ]; then
  mount /mnt/usb-storage
  HOSTNAME=`/bin/hostname`
  OWNER=`cat /mnt/usb-storage/.owner.$HOSTNAME`
  umount /mnt/usb-storage

  #remount as correct user
  sudo -u $OWNER mount /mnt/usb-storage

  # apply directory mappings
  HOMEDIR=`grep $OWNER /etc/passwd | awk -F: '{ print $6 }' `
  echo $HOMEDIR
  awk --assign homedir=$HOMEDIR --assign remover=$REMOVER -F= '
        {
                system( "mount --bind /mnt/usb-storage/" $1 " " homedir "/" $2 )
                system( "echo umount -f " homedir "/" $2 " >> " remover )
        }
        ' /mnt/usb-storage/.directory-map.$HOSTNAME

  echo "umount -f /mnt/usb-storage" >> $REMOVER
fi


This script requires
* Kernel 2.4 or higher
* file on the stick: .owner.$HOSTNAME
* file on the stick: .directory-map.$HOSTNAME
* every usb-stick-user must be able to "sudo mount"
* every usb-stick-user must be able to "mount /mnt/usb-stick" without resorting to sudo

How it works:
1) Mount the stick as root an read the file ".owner.HOSTNAME", where HOSTNAME is the local name. This file contains only a username; you can have a different username on each machine you use the stick on (very useful for taking stuff home from work!)
2) Unmount the root-mounted stick
3) Mount the stick again at the same position, but this time as the user; this action will give you correct permissions on the stick (extremely useful if you're not using FAT)
4) Now read ".directory-map.HOSTNAME", which again allows for one mapping per host. Every line in there is of the form "STICKDIR TARGETDIR". No wildcards/regexes allowed!
5) Bind /mnt/usb-stick/STICK-DIR to ~/TARGETDIR (this is like mounting, just different :wink: )
6) During all of that, keep the remove script up-to-date

The result: you can keep multiple directories on your stick (e.g. ~/Mail, ~/News, ~/ICQ/Logs), and have them mounted to the right directory automagically. You may remove the stick whenever it's not being accessed. You can do so on multiple machines, regardless of differences in username and layout of your homedir.

Hope that helps - have fun moving your data 8)

:!: WARNING: I've tried to keep out at least some obvious security holes. However, it's your machine and they're your users. Trust them or don't, but don't blame me if you get f*ucked using these scripts. The biggest flaw is keeping the user and directory mappings on the stick. If you know of any way to get around that please speak up.
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Mon Dec 15, 2003 6:50 pm    Post subject: Reply with quote

bedouin wrote:
#1: Data integrity
If you can live with really poor write performance then mount the device in synchronous mode:
Code:

/dev/sda1   /mnt/usb-storage      auto      sync,dirsync   0   0

That way data gets written to the stick immediately, your application will be blocked until the write is complete. Of course writing is quite slow, so don't use that for swap :wink:
On the other hand, there will be no stale buffers. It's OK to unplug whenever the stick is not being accessed.

The above line is the basis for everything described below.

#2: Automounting
I don't know about supermount (never used it) but for my stick I'm using the standard hotplug infrastructure: enable hotplug in the kernel and emerge sys-apps/hotplug. This will (among other things) give you scripts in /etc/hotplug.d and /etc/hotplug/<SUBSYSTEM> (for example: /etc/hotplug/usb)

The scripts in /etc/hotplug.d (usually just "default") will switch incoming hotplug events by subsystem, you'd modify that if have a new kind of hotplug system. Not interesting.

Now in /etc/hotplug/usb you would place scripts with the name of a kernel module, e.g. /etc/hotplug/usb/usb-storage, looking like this:

Code:

#!/bin/bash

# NOTE: to make this work, you *MUST* use the options "sync" and "dirsync" in your /etc/fstab !!!
#       otherwise you *WILL* lose data

#create a script to undo our actions upon removal
echo "#!/bin/bash" > $REMOVER
chmod a+x $REMOVER

if [ "$INTERFACE" = "8/6/80" ]; then
  mount /mnt/usb-storage
  echo "umount -f /mnt/usb-storage" >> $REMOVER
fi


This script will be executed when and if
* there is a USB hotplug event
* this event has already caused the module usb-storage.o to be loaded

The environment variables $REMOVER, $INTERFACE and $PRODUCT (and some others I don't remember) will be set by the hotplug infrastructure. The check for $INTERFACE=8/60/80 ensures that we are really dealing with a storage device. If your storage device needs special handling you might also check $PRODUCT (check your hotplug logs to find out your stick's product ID).

The file $REMOVER (if it exists) will be executed upon removal of the exact device it was created for.

The above script is all fine and dandy if you only have one user, one stick, and one location to mount it on. And else :?:

Well, try the following script for /etc/hotplug/usb/usb-storage, which is an extension of the previous example:
Code:

#!/bin/bash

# NOTE: to make this work, you *MUST* use the options "sync" and "dirsync" in your /etc/fstab !!!
#       otherwise you *WILL* lose data

#create a script to undo our actions upon removal
echo "#!/bin/bash" > $REMOVER
chmod a+x $REMOVER

# INTERFACE=8/6/80 means "mass storage device"
if [ "$INTERFACE" = "8/6/80" ]; then
  mount /mnt/usb-storage
  HOSTNAME=`/bin/hostname`
  OWNER=`cat /mnt/usb-storage/.owner.$HOSTNAME`
  umount /mnt/usb-storage

  #remount as correct user
  sudo -u $OWNER mount /mnt/usb-storage

  # apply directory mappings
  HOMEDIR=`grep $OWNER /etc/passwd | awk -F: '{ print $6 }' `
  echo $HOMEDIR
  awk --assign homedir=$HOMEDIR --assign remover=$REMOVER -F= '
        {
                system( "mount --bind /mnt/usb-storage/" $1 " " homedir "/" $2 )
                system( "echo umount -f " homedir "/" $2 " >> " remover )
        }
        ' /mnt/usb-storage/.directory-map.$HOSTNAME

  echo "umount -f /mnt/usb-storage" >> $REMOVER
fi


This script requires
* Kernel 2.4 or higher
* file on the stick: .owner.$HOSTNAME
* file on the stick: .directory-map.$HOSTNAME
* every usb-stick-user must be able to "sudo mount"
* every usb-stick-user must be able to "mount /mnt/usb-stick" without resorting to sudo

How it works:
1) Mount the stick as root an read the file ".owner.HOSTNAME", where HOSTNAME is the local name. This file contains only a username; you can have a different username on each machine you use the stick on (very useful for taking stuff home from work!)
2) Unmount the root-mounted stick
3) Mount the stick again at the same position, but this time as the user; this action will give you correct permissions on the stick (extremely useful if you're not using FAT)
4) Now read ".directory-map.HOSTNAME", which again allows for one mapping per host. Every line in there is of the form "STICKDIR TARGETDIR". No wildcards/regexes allowed!
5) Bind /mnt/usb-stick/STICK-DIR to ~/TARGETDIR (this is like mounting, just different :wink: )
6) During all of that, keep the remove script up-to-date

The result: you can keep multiple directories on your stick (e.g. ~/Mail, ~/News, ~/ICQ/Logs), and have them mounted to the right directory automagically. You may remove the stick whenever it's not being accessed. You can do so on multiple machines, regardless of differences in username and layout of your homedir.

Hope that helps - have fun moving your data 8)

:!: WARNING: I've tried to keep out at least some obvious security holes. However, it's your machine and they're your users. Trust them or don't, but don't blame me if you get f*ucked using these scripts. The biggest flaw is keeping the user and directory mappings on the stick. If you know of any way to get around that please speak up.


Looks like a nice script, you've got there.
But I'm affraid I'll keep using mine :), it's a bit less complicated.

Thanx for the feedback though.. I you don't mind I'll use some of your idea's in a next script.

Regards,

@@D
Back to top
View user's profile Send private message
bedouin
n00b
n00b


Joined: 19 Oct 2003
Posts: 4

PostPosted: Mon Dec 15, 2003 8:31 pm    Post subject: Reply with quote

Thanks for the kind words :)

I do admit that for single-user/single-host scenarios I'm committing serious overkill, but when writing it I had the explicit requirement of multi-user/multi-host.
To give a DB example: nobody said you couldn't use Oracle for a less-than-20-entries-ever guestbook on your homepage :twisted:

Of course you're free to use everything in there, I'd be delighted to see your next version.
Back to top
View user's profile Send private message
RedBeard0531
Guru
Guru


Joined: 21 Sep 2002
Posts: 415
Location: maryland

PostPosted: Mon Dec 15, 2003 9:44 pm    Post subject: Reply with quote

In this thread I posted about a solution that uses autofs/automountd. automounter unmounts the fs it it goes unaccessed for a set period of time. for a pen drive you can set it to 1sec for maximum safty. Will post more later, gotta run.

http://forums.gentoo.org/viewtopic.php?t=102158
_________________
OH MY GOD! Kenny just killed Kenny!
That Basterd!
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Tue Dec 16, 2003 1:04 am    Post subject: Script adjustments Reply with quote

Okey, well I adjusted the script a bit so it would fit my needs even more.

The stick is accessible by (config) definable users of the machine
(I use all the users gid=100, don't! if you are on a multiuser system!)
I am the only one that uses the stick on my computer, you can set up your own group and user in the top of the script (config part)

I inserted the sync and dirsync option that was advised by bedouin.
I hope it gives a bit of stability and robustness to the write process.

Code:

#!/bin/sh
# Shell script made by Eric Oud Ammerveld
# Dislclaimer : Should this script damage up your computer or stick in any way,
#               I'm not the one to blame.
#
#
# Run for ever
while [ 1 ] # Don't touch.. this is for the deamon to repeat
do          # start of while loop
 
#--------- CONFIG ------------#
#location of the stick (usually sd[x])
usbstick="sdb"
 
usbpart1="/dev/"$usbstick"1" #Partition 1 on the stick
mntpth1="/mnt/usb1" #Mount Path 1
fs1="vfat" #File system 1
 
usbpart2="/dev/"$usbstick"5" #Partition 2 on the stick (located in extended partition)
mntpth2="/mnt/usb2" #Mount Path 2
fs2="vfat" #File system 2 (vfat=dos/fat16/fat32 , ntfs ;type man mount for more fs)
 
allowedusr="1000"       #Allowed user to access stick
allowedgrp="100"        #Allowed group to access stick
#--------- CONFIG END---------#
 
 
#--------- SCRIPT STUPH BEGINNING ---------#
mntd="`/bin/mount | /bin/grep -c $usbstick`"
checkstick="`/bin/ls /dev |/bin/grep -c $usbstick`"
 
#/bin/echo "Amount of sticks :$checkstick" # A few debug rules
#/bin/echo "Mounted sticks :$mntd"
#/bin/echo "Partition 1: "$usbpart1
#/bin/echo "Partition 2: "$usbpart2
 
if [ $mntd == 0 ] # If the stick is not mounted...
then
  if [ $checkstick == 4 ] # Though the stick is detected...
  then
#    /bin/wall "USB Stick found! Mounting" # Globally written mounting message
    /bin/mount -o sync,dirsync,uid=$allowedusr,gid=$allowedgrp $usbpart1 $mntpth1 -t $fs1 # Mount it
    /bin/mount -o sync,dirsync,uid=$allowedusr,gid=$allowedgrp $usbpart2 $mntpth2 -t $fs2 # Mount it
  fi
else # is the stick IS mounted
  if [ $checkstick == 0 ] # If the stick isn't present...
  then
#    /bin/wall "USB Stick removed! Unmounting" #Globally wrutten unmounting message
    /bin/umount -f $mntpth1 > /dev/null # Unmount it
    /bin/umount -f $mntpth2 > /dev/null # Unmount it
  fi
fi
/bin/sleep 5 # Short time-out to reduce the load
done # end of while loop
#--------- SCRIPT STUPH END ---------#
Back to top
View user's profile Send private message
wmertens
n00b
n00b


Joined: 16 Dec 2003
Posts: 7
Location: Belgium

PostPosted: Tue Dec 16, 2003 11:06 am    Post subject: Here are /my/ scripts :) Reply with quote

This is what I made last year: http://sourceforge.net/mailarchive/message.php?msg_id=2673551

It works with Linux 2.4, and it doesn't need to know where the device appears. It even works when you plug in devices that have more than one partition, and it will mount them in a nice directory derived from the device name. In the story there's also a link to someone else's script that also generates a desktop entry pointing to the mount.

And recently I created a script for Linux 2.6. It works very well, much faster than the 2.4 version, and much more robust, too.

Code:

#!/bin/sh
#
# Automount hotplugged block devices, by Wout Mertens.
#
# Linux v2.6 version
# This script is released under version 2 of the GPL.

# To install this, either make it /sbin/hotplug, or, if you have
# linux-hotplug installed, make it /etc/hotplug.d/block/automount.hotplug .
# It needs to be executable. I tested it with busybox's ash.
#
# The devices will be mounted for the console user if applicable.
#
# To work, this needs:
# - v2.6 kernel support:
#   - hotplugging, /proc mounted, /sys mounted
#   - filesystems that will be mounted, like vfat
# - sh, echo, sed, stat or ls, getent or grep passwd,
#   mount, umount, mkdir, rmdir. logger is used if there.
#
# Possible improvements:
# - Create a desktop entry for the device.
# - Call a notifier script when mounting/unmounting. This could create the
#   desktop entry by itself, and could call user scripts from their homedir
# - Mount as supermount if available. This will improve behaviour for
#   synchronous writes and hanging mounts, although umount -lf already
#   does a good job.
# - Detect filesystem on device, so filesystems that don't need a mounting
#   user can skip user detection.

# Debugging
# set -xv
# exec > /tmp/hotplug.$$ 2>&1

PATH="/bin:/sbin:/usr/bin:/usr/sbin"
export PATH

# We only handle block device messages
[ "$1" != "block" ] && exit 0

# Proclaim stuff to the world
mesg () {
        logger -t $0 "$*"
}

# Is path already mounted?
is_path_mounted () {
        while read dev path rest
        do
                if [ "$path" = "$1" ]
                then
                        return 0
                fi
        done < /proc/self/mounts
        return 1
}

# Get mounted path for a device
get_mounted_path () {
        while read dev path rest
        do
                if [ "$dev" = "$1" ]
                then
                        echo "$path"
                        return 0
                fi
        done < /proc/self/mounts
        return 1
}

# Wait for a file to appear
wait_for () {
        local count=0
        while [ $count -lt 10 ] && [ ! -e "$1" ]
        do
                sleep 1
        done
        [ $count -eq 10 ] && return 1
        return 0
}

# Remove strange characters from a filename
clean_filename () {
        # Note the lack of quotes around $1, this strips off spaces.
        echo $1 | sed 's/[ /?*\"<>]/_/g'
}

# Figure out the device to mount
set `echo $DEVPATH | sed 's/\// /g'`
[ $# -ne 3 ] && exit 0
DEVICE=/dev/$3

if [ "$ACTION" = "remove" ]
then
        # Is it ours?
        dir=`get_mounted_path $DEVICE`
        echo "$dir" | grep -q ^/mnt/usb || exit 0

        # Unmount it
        [ -d "$dir" ] || exit 1
        umount -lf "$dir"
        rmdir "$dir"
        exit 1
fi

if [ "$ACTION" = "add" ]
then
        # Is it a usb device? Exit if not.
        ls -l /sys/$1/$2/device | sed 's/^.* -> //g' | grep -q usb || exit 0

        # Mount it

        # Make sure we have support for vfat
        modprobe -q vfat

        wait_for /sys/$1/$2/device/vendor || exit 1

        # Find the name
        PRODUCT=`cat /sys/$1/$2/device/model`
        if [ -z "$PRODUCT" ]
        then
                PRODUCT=generic
        fi
        # Find out where we mount it
        MOUNTPATH=/mnt/usb/`clean_filename "$PRODUCT"`
        if is_path_mounted "$MOUNTPATH"
        then
                count=1
                while is_path_mounted "${MOUNTPATH}_${count}"
                do
                        count=$(( $count + 1 ))
                done
                MOUNTPATH="${MOUNTPATH}_${count}"
        fi
        # Make sure it's a directory
        if [ -e "$MOUNTPATH" ]
        then
                if [ ! -d "$MOUNTPATH" ]
                then
                        mesg "$MOUNTPATH exists but is not a directory"
                        exit 1
                fi
        else
                mkdir -p "$MOUNTPATH"
                if [ $? -ne 0 ]
                then
                        mesg "Could not create mountpoint $MOUNTPATH"
                        exit 1
                fi
        fi
        # Find out who we are going to mount it as
        CONSOLEUSER=`stat -c%U /dev/console 2>/dev/null`
        if [ -z "$CONSOLEUSER" ]
        then
                set `ls -l /dev/console`
                CONSOLEUSER=$3
        fi
        [ -n "$CONSOLEUSER" ] || CONSOLEUSER=root
        PASSWD=`getent passwd $CONSOLEUSER 2>/dev/null`
        if [ -z "$PASSWD" ]
        then
                PASSWD=`grep "$CONSOLEUSER" /etc/passwd||grep root /etc/passwd`
        fi
        if [ -z "$PASSWD" ]
        then
                mesg "Could not get password entry for $CONSOLEUSER"
                exit 1
        fi
        set `echo $PASSWD | sed 's/:/ /g'`
        if [ $# -lt 4 ]
        then
                mesg "Bad password entry for $CONSOLEUSER"
                exit 1
        fi

        # These options should prevent abuse and make it writeable for the
        # console user.
        MOUNTOPTS="-s -osync,dirsync,nosuid,umask=077,uid=$3,gid=$4"
        mesg Mounting $DEVICE on $MOUNTPATH, options $MOUNTOPTS

        mount $MOUNTOPTS $DEVICE $MOUNTPATH
fi


Enjoy :wink:

Update: Download the latest version at http://dev.gentoo.org/~wmertens/automount.hotplug


Last edited by wmertens on Wed Dec 17, 2003 8:57 am; edited 1 time in total
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Tue Dec 16, 2003 6:12 pm    Post subject: Reply with quote

Amai!! Dat is een behoorlijke lap code ;) >wmertens
(Dutch for something like : Cribbeley Sjizzels, that's quite a typing work ;))
_________________
Linux IS userfriendly,
It's only very selective about who it's friends are.

-=@@D=-
Back to top
View user's profile Send private message
wmertens
n00b
n00b


Joined: 16 Dec 2003
Posts: 7
Location: Belgium

PostPosted: Tue Dec 16, 2003 10:28 pm    Post subject: Reply with quote

Cut'n'paste is your friend 8)
Back to top
View user's profile Send private message
genotix
n00b
n00b


Joined: 10 Dec 2003
Posts: 13
Location: The Netherlands

PostPosted: Tue Dec 16, 2003 10:59 pm    Post subject: Reply with quote

wmertens wrote:
Cut'n'paste is your friend 8)


That's not what they teach us @ school ;)
_________________
Linux IS userfriendly,
It's only very selective about who it's friends are.

-=@@D=-
Back to top
View user's profile Send private message
eonnen
n00b
n00b


Joined: 03 Dec 2003
Posts: 7

PostPosted: Tue Dec 16, 2003 11:11 pm    Post subject: Reply with quote

A thought and a question:

Thought: You probably want to mount with a noatime option. You have about 10,000 erase/write cycles on typical flash media and when mounted with atime, a simple 'ls' will result in an atime update shortening the life of your device. See http://www.linuxjournal.com/article.php?sid=6867 for a better explanation.

Question: Are you certain that sync and dirsync are honored by vfat? I'm looking at the man for mount and it says only ext2/ext3/ufs honor sync options. Just curious as I'm not using them as mount options for my drive and I haven't had a problem _yet_.
_________________
I have no idea what I'm doing.
Back to top
View user's profile Send private message
nukem996
l33t
l33t


Joined: 13 Nov 2003
Posts: 770

PostPosted: Wed Dec 17, 2003 3:20 am    Post subject: Reply with quote

I just got a memory stick today and configed it under redhat, still havnt set it up on my gentoo system. You need to enable USB mass storage and some more things in your kernel and add to fstab

/dev/sda1 /mnt/usb/ auto noauto,user,rw 0 0
Back to top
View user's profile Send private message
wmertens
n00b
n00b


Joined: 16 Dec 2003
Posts: 7
Location: Belgium

PostPosted: Wed Dec 17, 2003 8:55 am    Post subject: Reply with quote

eonnen wrote:

Thought: You probably want to mount with a noatime option. You have about 10,000 erase/write cycles on typical flash media and when mounted with atime, a simple 'ls' will result in an atime update shortening the life of your device. See http://www.linuxjournal.com/article.php?sid=6867 for a better explanation.


Good point. Adding that to my script; you can download the latest version at http://dev.gentoo.org/~wmertens/automount.hotplug

eonnen wrote:

Question: Are you certain that sync and dirsync are honored by vfat? I'm looking at the man for mount and it says only ext2/ext3/ufs honor sync options. Just curious as I'm not using them as mount options for my drive and I haven't had a problem _yet_.


Well, sync is honoured but dirsync isn't. Sigh. Type "sync" a few times before you unplug it, or get supermount_ng installed. It's ported to 2.6: http://supermount-ng.sourceforge.net/ .

I added a test, but I didn't test if my script actually works with it, though :oops:
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Kernel & Hardware All times are GMT
Goto page 1, 2, 3  Next
Page 1 of 3

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum