2008年10月24日 星期五

Auto-mount usb-storage on OS using the udev mechanism

1. crate one new rule "30-usbstorage.rules" in the "/etc/udev/rule.d/":

BUS=="usb", KERNEL=="sd*",ACTION=="add",NAME="%k", MODE="0660", GROUP="floppy", SYMLINK+="disks/Removable/%k", RUN+="/home/user/mount_usb.sh %k"
KERNEL=="sd*[!0-9]",ACTION=="remove", RUN+="/home/user/umount_usb.sh %k"

2. create "/home/user/mount_usb.sh"

#!/bin/sh

export DISPLAY=:0.0
dev=""
test -f /home/user/.bash_profile && source /home/user/.bash_profile

save_mount_db (){
pid=""
if mountpoint -q $2;then
if ! cat /tmp/mount_db | grep $1":"$2;then
/home/user/appletui $1 $2 "/usr/bin/konqueror" /home/user/umount_usb.sh&
pid=`ps aux | grep "$1 $mount_point" | cut -d' ' -f7`
echo $1":"$mount_point":"$pid >> /tmp/mount_db
echo "`date`: mount $1 :OK!" >> /tmp/usb.log

fi
fi
}
do_mount(){

mount_point=/media/$1
fstype=`/usr/bin/disktype /dev/$1 | grep "file system" | cut -d'f' -f1`
if mountpoint -q $mount_point;then
umount -l $mount_point
rm -fr $mount_point
fi
if ! mountpoint -q $mount_point;then

case "$fstype" in
*Ext3*)

mkdir -v $mount_point
mount -t ext3 -o rw,user,sync,suid,dev,exec /dev/$1 $mount_point
chmod 777 $mount_point
save_mount_db $1 $mount_point
;;
*Ext2*)
mkdir -v $mount_point
mount -t ext2 -o rw,user,sync,suid,dev,exec /dev/$1 $mount_point
chmod 777 $mount_point
save_mount_db $1 $mount_point
;;
*FAT12* | *FAT16* | *FAT32*)
mkdir -v $mount_point
mount -t vfat -o rw,user,flush,noexec,nosuid,nodev,fmask=111,dmask=0,iocharset=utf8,shortname=mixed /dev/$1 $mount_point
chmod 777 $mount_point
save_mount_db $1 $mount_point
;;
*Reiserfs*)
mkdir -v $mount_point
mount -t reiserfs -o rw,user,suid,dev,exec,sync /dev/$1 $mount_point
chmod 777 $mount_point
save_mount_db $1 $mount_point
;;
*)echo "`date`: mount $1 :NOT OK!" >> /tmp/usb.log;;
esac
fi
}



if /usr/bin/disktype /dev/$1 | grep Partition;then

/usr/bin/disktype /dev/$1 | grep Partition | cut -d: -f1 > /tmp/testmount.log
i=0;
cat /tmp/testmount.log| while read partition
do
i=$((i+1))
dev=$1$i
do_mount $dev

done
rm -f /tmp/testmount.log
else

dev=$1
do_mount $dev

fi


3. create "/home/user/umount_usb.sh"

#!/bin/sh


export DISPLAY=:0.0

dev=""

echo `date`":"$1 >> /tmp/umount_usb.log

test -f /home/user/.bash_profile && source /home/user/.bash_profile

i=0;
mount_point=""
line=""
pid=""
if [ -f /tmp/mount_db ];then
if cat /tmp/mount_db | grep $1;then
mount_point=`cat /tmp/mount_db | grep -n $1 | cut -d: -f3`
line=`cat /tmp/mount_db | grep -n $1 | cut -d: -f1`
pid=`cat /tmp/mount_db | grep -n $1 | cut -d: -f4 | cut -d' ' -f1 `

if mountpoint -q $mount_point ;then
umount -l $mount_point
rm -fr $mount_point
sed -e $line'd' /tmp/mount_db > /tmp/mount_db.tmp
mv /tmp/mount_db.tmp /tmp/mount_db
kill -9 $pid
exit
fi
fi
exit
fi
echo "no /tmp/mount_db"
4. insert one usb storage disk into computer,and use "udevadm --monitor" to monitor the condition

沒有留言: