Bash Script to Detect When My Usb Is Plugged in and to Then Sync It with a Directory

How to execute a shellscript when I plug-in a USB-device

If you want to run the script on a specific device, you can use the vendor and product ids

  • In /etc/udev/rules.d/test.rules:

    ATTRS{idVendor}=="152d", ATTRS{idProduct}=="2329", RUN+="/tmp/test.sh"
  • in test.sh:

    #! /bin/sh

    env >>/tmp/test.log
    file "/sys${DEVPATH}" >>/tmp/test.log

    if [ "${ACTION}" = add -a -d "/sys${DEVPATH}" ]; then
    echo "add ${DEVPATH}" >>/tmp/test.log
    fi

With env, you can see what environment is set from udev and with file, you will discover the file type.

The concrete attributes for your device can be discovered with lsusb

lsusb

gives

...

Bus 001 Device 016: ID 152d:2329 JMicron Technology Corp. / JMicron USA Technology Corp. JM20329 SATA Bridge

...

How can I listen for 'usb device inserted' events in Linux, in Python?

Update: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and udev, I keep the Hal version for historical reasons.

This is basically the example in the pyudev documentation, adapted to work with older versions, and with the glib loop, notice that the filter should be customized for your specific needing:

import glib

from pyudev import Context, Monitor

try:
from pyudev.glib import MonitorObserver

def device_event(observer, device):
print 'event {0} on device {1}'.format(device.action, device)
except:
from pyudev.glib import GUDevMonitorObserver as MonitorObserver

def device_event(observer, action, device):
print 'event {0} on device {1}'.format(action, device)

context = Context()
monitor = Monitor.from_netlink(context)

monitor.filter_by(subsystem='usb')
observer = MonitorObserver(monitor)

observer.connect('device-event', device_event)
monitor.start()

glib.MainLoop().run()

Old version with Hal and d-bus:

You can use D-Bus bindings and listen to DeviceAdded and DeviceRemoved signals.
You will have to check the capabilities of the Added device in order to select the storage devices only.

Here is a small example, you can remove the comments and try it.

import dbus
import gobject

class DeviceAddedListener:
def __init__(self):

You need to connect to Hal Manager using the System Bus.

        self.bus = dbus.SystemBus()
self.hal_manager_obj = self.bus.get_object(
"org.freedesktop.Hal",
"/org/freedesktop/Hal/Manager")
self.hal_manager = dbus.Interface(self.hal_manager_obj,
"org.freedesktop.Hal.Manager")

And you need to connect a listener to the signals you are interested on, in this case DeviceAdded.

        self.hal_manager.connect_to_signal("DeviceAdded", self._filter)

I'm using a filter based on capabilities. It will accept any volume and will call do_something with if, you can read Hal documentation to find the more suitable queries for your needs, or more information about the properties of the Hal devices.

    def _filter(self, udi):
device_obj = self.bus.get_object ("org.freedesktop.Hal", udi)
device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device")

if device.QueryCapability("volume"):
return self.do_something(device)

Example function that shows some information about the volume:

     def do_something(self, volume):
device_file = volume.GetProperty("block.device")
label = volume.GetProperty("volume.label")
fstype = volume.GetProperty("volume.fstype")
mounted = volume.GetProperty("volume.is_mounted")
mount_point = volume.GetProperty("volume.mount_point")
try:
size = volume.GetProperty("volume.size")
except:
size = 0

print "New storage device detectec:"
print " device_file: %s" % device_file
print " label: %s" % label
print " fstype: %s" % fstype
if mounted:
print " mount_point: %s" % mount_point
else:
print " not mounted"
print " size: %s (%.2fGB)" % (size, float(size) / 1024**3)

if __name__ == '__main__':
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
DeviceAddedListener()
loop.run()

Drive name in batch

find the correct drive letter:

for /f "usebackq tokens=2 delims=:=" %%a in (`wmic logicaldisk where VolumeName^="John's usb" get caption /value`) do set drive=%%a:
if "%drive%"=="" (
echo not inserted
) else (
echo inserted as %drive%
)

Bash script does not wait for cp

Adding a sync at the end solved it. Thanks to Jite

# Enable LED
/home/pi/project/src/led.sh 8 1

data="/home/pi/project/data/"
olddata="/home/pi/project/data/olddata/"
backup="/media/usbstick/backup/"
dateFolder=""

# Get current time
t=$(date +"%y-%m-%d_%H-%M")

# Check backup directory
if [ ! -d "$backup" ]; then
mkdir $backup
fi
dateFolder="${backup}backup_${t}/"

# Check dataFolder directory
if [ ! -d "$dateFolder" ]; then
mkdir $dateFolder
fi
# Check olddatq directory
if [ ! -d "$olddata" ]; then
mkdir $olddata
fi

# First copy all data to usb stick
find "${data}" -maxdepth 1 -mindepth 1 ! -iname "olddata" \
| xargs -I {} cp -r {} $dateFolder
# Then move the data to olddata
find "${data}" -maxdepth 1 -mindepth 1 ! -iname "olddata" \
| xargs -I {} mv {} $olddata

sync

# Disable red LED, enable green
/home/pi/project/src/led.sh 8 0
/home/pi/project/src/led.sh 7 1


Related Topics



Leave a reply



Submit