Skip to content
Advertisement

Copy file to USB automatically on mount Raspberry Pi

I’m currently doing a project which requires a file to be automatically copied to USB-stick on mount. Based on my research in internet, I believe it is doable using udev rule. So, when an USB is inserted into my RPi2, the udev rule will then execute a python script which allows file to be copied to the USB-stick.

Problem is, I also heard that the script will be executed before the RPi mount the USB, which means the file will not be copied. Is there a solution to this? The python script was executed when i copied the file internally (on RPi itself not USB), it just doesn’t work when I tried to copy it to USB.

Below are my code:

Udev rule

KERNEL=="sd*1", ACTION=="add", RUN=="/home/pi/datalogger/autocopy.sh"

Shell script

cd /
cd /home/pi/datalogger
sudo /usr/bin/python autocopy.py
cd / 
exit

Python script

import shutil
import datetime

# File to be copied
source = "/home/pi/copied.txt"

# USB name must be changed to 'USB1' in order for auto copy to work
destination = "/media/pi/USB1/datalogger_backup_%s.txt" % datetime.datetime.now().date()

try:
   # Copy file to destination
   shutil.copy2(source, destination)
   # E.g. source and destination is the same location
except shutil.Error as e:
   print("Error: %s" % e)
   # E.g. source or destination does not exist
except IOError as e:
   print("Error: %s" % e.strerror)

Advertisement

Answer

Question: … the destination is not available as the USB is yet to be mounted

Add the following to your script to verify the mount status:

mount >> /tmp/mount.log

Read this auto-mounting-usb-storage/
Maybe you can adapt to your needs.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement