how to execute a script every time any USB get mounted

6,538

Solution 1

write a udev rule which first mounts the USB-drive and second runs my-script

# cat /etc/udev/rules.d/11-media-by-label-with-pmount.rules

KERNEL!="sd[a-z]*", GOTO="media_by_label_auto_mount_end"
ACTION=="add", PROGRAM!="/sbin/blkid %N", GOTO="media_by_label_auto_mount_end"

# Get label
PROGRAM=="/sbin/blkid -o value -s LABEL %N", ENV{dir_name}="%c"

# use basename to correctly handle labels such as ../mnt/foo
PROGRAM=="/usr/bin/basename '%E{dir_name}'", ENV{dir_name}="%c"
ENV{dir_name}=="", ENV{dir_name}="usbhd-%k"

ACTION=="add", ENV{dir_name}!="", RUN+="/bin/su YOURUSERNAME -c '/usr/bin/pmount %N %E{dir_name}'", RUN+="/etc/udev/scripts/my-script.sh"
ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/su YOURUSERNAME -c '/usr/bin/pumount /media/%E{dir_name}'"
LABEL="media_by_label_auto_mount_end"

note: The drive is mounted by root but can be unmounted by the given user. In the last block you have to change YOURUSERNAME with your username and /etc/udev/scripts/my-script.sh with the path to your script. Source and more scripts: https://wiki.archlinux.de/title/Udev#USB_Ger.C3.A4te_automatisch_einbinden


Another solution is to use a udisks wrapper like devmon.

Solution 2

Linux has no hook that runs when a device is mounted in all circumstances.

Udev handles devices when they appear in the system. It can run a command at that point (example). Although you can run mount from udev, this conflicts with Udisks, and in particular doesn't work on systems using systemd. It's possible to monitor mounts performed by Udisks, but I don't know how to do that from the command line. There's a Python example on the Gentoo wiki.

There is a facility to monitor arbitrary system calls: the audit system. The following command triggers a log entry whenever the mount system call returns:

auditctl -a exit,always -S mount

You can trigger a program from an audit event via audisp, but this isn't very convenient: you need to write a plugin that parses the audit event.

Share:
6,538

Related videos on Youtube

schmiddl
Author by

schmiddl

Updated on September 18, 2022

Comments

  • schmiddl
    schmiddl over 1 year

    I use a script that writes all mountpoints of my devices to a textfile using df. How can I execute my script every time any device (especially USB) is mounted?

    script to execute:

    #!/bin/bash
    # save all mountpoints to textfile
    df -h /dev/sd*| grep /dev/sd| awk '{print $6}' > /home/<user>/FirstTextfile
    # do something
    while read line 
    do  
    echo "mountpoint:${line%/*}/ devicename:${line##*/}}" >> home/<user>/AnotherTextfile
    

    Debian 8.0 (jessie), Linux 3.16.0, Gnome 3.14.

  • mikeserv
    mikeserv almost 9 years
    Or findmnt --poll.