Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  10] [ 0]  / answers: 1 / hits: 30966  / 2 Years ago, tue, december 21, 2021, 11:44:57

I am trying to run a script whenever a pendrive is connected to my system.
I followed this and this question and it is working, but there are still some problems.


This is my udev rules file:


ACTION=="add", ATTRS{idVendor}=="8564", ATTRS{idProduct}=="1000", RUN+="/usr/local/my_script.sh"

And this is my script:


#!/bin/bash

env > /tmp/env.out
cp -r /media/*device-name*/* ~/test/

I have two questions:



  1. Whenever I plug my USB device in, the script is executed because a file env.out is generated in /tmp, but the data from the USB device are not copied to the test directory.


    If I run the script manually, it works fine! Why?



  2. How can I make my rules file more general so that it will work for any USB device which is connected without knowing its ID?




My idea behind this is to copy all the data from any connected USB device to my computer automatically when it is connected.


More From » usb

 Answers
6

To answer my own question:


1. The script was not running because it needed sudo rights to run.


To solve this, make this script sudo executable:



  • Edit the sudoers file using:


    sudo visudo


  • After line 25 (i.e %sudo ALL=(ALL)) add this:


    username  ALL=(ALL) NOPASSWD: /home/username/my_script.sh



Now we can use sudo in this script without being asked for the sudo password. However, this may cause some security problems, so please refer to this question: How do I sudo a command in a script without being asked for a password?


2. Answer to my second question:


To make this script work for any USB device which is connected, change the udev rules file's content to this:


ACTION=="add", ATTRS{idVendor}=="`****`", ATTRS{idProduct}=="`****`", RUN+="/usr/local/my_script.sh"

The asterik (*) tells that this should be done for every USB device connected.


That's it! Make sure that script is executable and plug your USB in!


ENjoy!


[#27622] Wednesday, December 22, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tresein

Total Points: 197
Total Questions: 113
Total Answers: 112

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
tresein questions
Tue, Jun 28, 22, 17:57, 2 Years ago
Sun, Apr 3, 22, 07:11, 2 Years ago
Thu, Feb 3, 22, 18:03, 2 Years ago
Sat, May 13, 23, 13:00, 1 Year ago
;