About udev.

How to mount a usb-stick by certain rules and conditions?

For example how to mount a flash drive with a specific uuid in read-only mode, but at the same time the rest of the drives are mounted in rw mode.

All this is easily realized using the rules of udev.

Before using of udev rules in Ubuntu, for example, we should disable the automatic mounting. This can be done through a gconf-editor call and then through disabling of media_automount in the properties of nautilus.

If there is no such property in gconf-editor, it is possible to disable the automatic connection using the utility gnome-disks.

Now let's talk about creating rules:

The rule is a file in the folder /etc/udev/rules.d

The file name is to begin with a numeric symbol and to end with .rules, for example: 10-automnt.rules

The line in the file as shown below will mean that while connecting the flash drive it have to be mounted to home/mnt

SUBSYSTEM=="block", KERNEL=="sd[c-z][0-9]", ACTION=="add", RUN+="/bin/mount -O uid=1000 /dev/%k /home/mnt

ACTION=="add" - device connection

RUN+= - that what is to be done, when this event occurs

To unmount the flash drive while disconnecting we should write the following:

SUBSYSTEM=="block", KERNEL=="sd[c-z][0-9]", ACTION=="remove", RUN+="/bin/umount /home/mnt"

ACTION=="remove" - device disconnecting.

After modifying the file 10-automnt.rules and to apply these changes we should run the following command:

$ udevadm config --reload-rules

For getting information about what attributes in udev can be operated towards a particular device we should run the following command:

$ udevadm info -a -n /dev/sdc1

Or we can run udevadm in the monitor mode and connect a usb-stick at this moment:

$ udevadm monitor --property --kernel --udev

All existing attributes that gives udevadm can be used in the line of the rules. For example, the following line will be executed regarding to devices with the serial number:

SUBSYSTEM=="block", KERNEL=="sd[b-z][0-9]", ATTRS{serial}=="0013728A7896EA61C0000000" ACTION=="add", RUN+="/home/mnt_script.sh %k"

Conditions can be summarized as follows:

SUBSYSTEM=="block", KERNEL=="sd[b-z][0-9]",ATTRS{speed}=="12", ATTRS{serial}=="0013728A7896EA61C0000000" ACTION=="add", RUN+="/home/mnt_script.sh %k"