Запуск скрипта при подключении usb linux

unixforum.org

Ось Debian etch, KDE..
При подключении флешки можно вызвать исполняемый скрипт, запихав
/etc/udev/rules.d
правило типа:
KERNEL==»sd*», SUBSYSTEMS==»usb», ACTION==»add», RUN=»/root/test.sh»
срабатывает нормально.
Вопрос: почему не работает если добавить:
KERNEL==»sd*», SUBSYSTEMS==»usb», ACTION==»remove», RUN+=»/root/test_remove.sh»
?? в чем косяк?
Можно ли вообще отловить данное событие — как извлечение флешки?

Minton Сообщения: 1588 Статус: openSUSE Localization Team ОС: openSUSE Tumbleweed x86-64

Re: запуск скрипта при извлечении флешки

Сообщение Minton » 15.06.2009 13:16

Тут куча вариантов: уверены ли вы, что событие называется remove? Уверены ли вы, что во втором случае надо писать +=, а не =, как в первом? А скрипт этот точно исполняемый?

«Настоящие мужчины используют поиск» ©Goodvin

Re: запуск скрипта при извлечении флешки

Сообщение zshgm » 15.06.2009 13:51

с помощью udevmonitor —env
при вытаскивании флешки вижу (действие remove происходит):
UDEV [1245059664.359228] remove@/block/sdb
UDEV_LOG=3
ACTION=remove
DEVPATH=/block/sdb
SUBSYSTEM=block
SEQNUM=1267
MINOR=16
MAJOR=8
PHYSDEVPATH=/devices/pci0000:00/0000:00:1d.7/usb5/5-7/5-7:1.0/host12/target12:0:0/12:0:0:0
PHYSDEVBUS=scsi
PHYSDEVDRIVER=sd
UDEVD_EVENT=1
ID_VENDOR=JetFlash
ID_MODEL=Transcend_32GB
ID_REVISION=8.07
ID_SERIAL=JetFlash_Transcend_32GB_4JRWAUI1
ID_TYPE=disk
ID_BUS=usb
ID_PATH=pci-0000:00:1d.7-usb-0:7:1.0-scsi-0:0:0:0
DEVLINKS=/dev/disk/by-id/usb-JetFlash_Transcend_32GB_4JRWAUI1 /dev/disk/by-path/pci-0000:00:1d.7-usb-0:7:1.0-scsi-0:0:0:0
DEVNAME=/dev/sdb

комбинировал различные варианты, событие add срабатывает всегда, а remove -никогда : /

скрипт исполняемый, точно такой же скрипт(с другим именем) успешно выполняется при подключении флешки
-rwxr-xr-x 1 root root 48 2009-06-15 14:04 test_remove.sh

Источник

How to run a script when a specific flash-drive is mounted?

Is there a way to run a script when a particular USB device is mounted? I keep my videos on a separate USB and would like to run a script that would mount the video folder on the USB device to the one in the home folder.

6 Answers 6

There’s much nicer solution with systemd now. You create a service which depends and is wanted by you media e.g.: /etc/systemd/system/your.service

[Unit] Description=My flashdrive script trigger Requires=media-YourMediaLabel.mount After=media-YourMediaLabel.mount [Service] ExecStart=/home/you/bin/triggerScript.sh [Install] WantedBy=media-YourMediaLabel.mount 

Then you have to start/enable the service:

sudo systemctl start your.service sudo systemctl enable your.service 

After mount, systemd fires your trigger script. The advantage over udev rule is that the script really fires after mount, not after adding system device.

Читайте также:  Отложенное выполнение команды linux

Use case: I have an encrypted partition which I want to backup automatically. After adding the device I have to type in the password. If I hooked the backup script to udev, the script attempts to run at the time when I’m typing password, which will fail.

Note: You can find your device unit with:

systemctl list-units -t mount 

I hope april 2016 is coming soon. The next Ubuntu LTS will have systemd enabled. AFAIK the nice solution from above needs Ubuntu 15.04 or newer.

Great! Tested in Debian Jessie. Don’t forget to enable your service systemctl enable your.service . The script file must be executable.

For me, this fails. When I try to start the service, it complains with «Unit media-bb.mount not found.». I called my thumb drive’s (FAT32) FS «bb» to make sure there are no weird characters in it and it’s not too long or anything like this. I tried the Requires= , After= , and WantedBy= lines both with media-bb.mount and media-BB.mount because Nautilus shows me the volume as «BB», not «bb». Same error message, except for capitalization. What’s wrong? Do I somehow have to create that media-.mount service?

@StevenJeffries systemctl list-units -t mount gives you that label. Systemd automatically creates .mount units and as far as I can tell, it’s a mount path, but with slashes ( / ) replaced by dashes ( — ). And one note: this unit also works as a user unit ( systemctl —user ).

Start by finding your device in lsusb . Note the ID (eg 0a81:0101 )

Create a new udev rules file in /etc/udev/rules.d/ via sudoedit /etc/udev/rules.d/100-mount-videos.rules and plonk a new rule in there like this:

ACTION=="add", ATTRS=="0a81", ATTRS=="0101", RUN+="/home/your_username/bin/mount_videos.sh" 

Note how I used the ID from lsusb .

Then you just need to write the script to do the work. A simple mount command should work. You might need a sleep 5 command in there to wait for the filesystem to initialize (if you leave gnome to do the main mounting — but you’re free to mount it first and then you might not need the sleep).

Читайте также:  Online courses in linux

Addition from Allan: Long running scripts might block «all further events for this or a dependent device». My Mint man page further states «Long running tasks need to be immediately detached from the event process itself.» No tip is given on where to gain the skill to do this.

Источник

How to run custom scripts upon USB device plug-in?

What is the state-of-the-art method for automatically executing custom scripts upon USB device plug-in under current Linux distributions like Debian/CentOS/Fedora? For example if you want to automatically mount/copy some files/umount a USB mass storage device based on its UUID (or device ID etc.).

2 Answers 2

Put a line like this in a file in /etc/udev/rules.d :

KERNEL=="sd*", ATTRS=="Yoyodyne", ATTRS=="XYZ42", ATTRS=="123465789", RUN+="/pathto/script" 

Add a clause like NAME=»subdir/mydisk%n» if you want to use a custom entry path under /dev .

Run udevadm info -a -n sdb to see what attributes you can match against ( attribute==»value» ; replace sdb by the device name automatically assigned to the disk, corresponding to the new entry created in /dev when you plug it in). Note that you can use ATTRS clauses from any one stanza: you can pick any stanza, but the ATTRS clauses must all come from the same stanza, you can’t mix and match. You can mix ATTRS clauses with other types of clauses listed in a different stanza.

Is this answer still valid? Under no amount of fiddling can I get the script to execute (and touch a file). If you can provide the most basic example that executes a script when anything is plugged in, that would be great and we can work from there.

@Redsandro I have variations of this rule in my udev configuration and they’re working. Did you plug the device out and back in, or run udevadm trigger ? Does your system use udev? If you want to run a script when anything is plugged in, remove all the conditions (the clauses with == ) (maybe the syntax requires one condition, I’m not sure; if it does, use KERNEL==»*» ).

Читайте также:  Linux absolute path to file

I tried that too, but since it works for you, I must be missing a step. I have moved this question here, so I can write example code.

Perhaps related, I think there is a time limit on how long the script may run. I believe it is very short (like 1 second or something). If it takes longer than that, then udev will kill it. You can work around this by using backgrounding the script with something like at . See «running external programs» on reactivated.net/writing_udev_rules.html

Just to add to this, for the sake of completeness, the file needs to have the suffix .rules and the files in the directory are read in a lexical order (convention uses numeric prefix to order them), and they can be beneath /etc/ , /usr/lib or /run . For more, RTFM.

I looked in /lib/udev/rules.d for examples of disk related rules. On an Ubuntu system one rule file provides the environment variable ID_FS_UUID_ENC which you can use in own rule files.

Thus I put a custom rule file under /etc/udev/rules.d/foodevice.rules . Since it is not prefixed with a number, it is ran at last by udev. Btw, the udev daemon watches /etc/udev/rules.d for changes such that you don’t need to restart it on file changes.

The content of /etc/udev/rules.d/foodevice.rules is:

ACTION=="add", KERNEL=="sd*[!0-9]", ENV=="FFFF-AAAF", RUN+="/usr/bin/sudo -u juser /home/juser/path/script.sh" 

(this is one rule — you have to remove the newline after the ENV clause because udev does not have a line continuation mechanism)

A program started by udev blocks the daemon — thus it shouldn’t run for a long time. I solved it via at — i.e. via detaching from the process doing the real work:

$ cat /home/juser/path/script.sh #!/bin/sh echo /path/to/mountcopystuff.sh | at now 

Источник

Оцените статью
Adblock
detector