How can I automatically copy the content of a usb (flash) drive to another directory?

20,590

The script below is an opposite- variant of this script; while that one acts on specified drives, this scripts acts on all except specified (usb) drives.

What it does

  • Whenever an external usb storage device is being connected, the script copies its content into a directory, defined by you (in the head section of the script: target_folder =). A sub directory is created with the name of the drive it was copied from.
  • If the target folder (earlier copy of the disk's content) exists, it overwrites the earlier copy.
  • I also added an entry excluded =, in which you can (and probably should) list the names of your "normal", (permanent) usb devices ("normal" drives are excluded already automatically). it seems Ubuntu defines the type of device mainly by the file system; I tested formatting a flash drive as ext4, and it showed up as a "normal" drive instead of a flash drive.

The script

#!/usr/bin/env python3

import subprocess
import time
import shutil

#--
target_folder = "/path/to/target_folder"
excluded = ["media_extern"]
#--

def get_mountedlist():
    return [(item.split()[0].replace("├─", "").replace("└─", ""),
             item[item.find("/"):]) for item in subprocess.check_output(
            ["/bin/bash", "-c", "lsblk"]).decode("utf-8").split("\n") if "/" in item]

def identify(disk):
    command = "find /dev/disk -ls | grep /"+disk
    output = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
    if "usb" in output:
        return True
    else:
        return False

done = []
while True:
    mounted = get_mountedlist()
    new_paths = [dev for dev in get_mountedlist() if not dev in done and not dev[1] == "/"]
    valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split("/")[-1]  in excluded) == (True, False)]
    for item in valid:
        target = target_folder+"/"+item[1].split("/")[-1]
        try:
            shutil.rmtree(target)
        except FileNotFoundError:
            pass
        shutil.copytree(item[1], target)
    done = mounted
    time.sleep(4)

How to use

Copy the script into an empty file. In the head section, set:

  • the path to where you want to store the copies of your inserted flash drives

    target_folder = "/path/to/directory"
    
  • the names of your possibly permanently connected devices (use lsblk if you don't know)

    excluded = ["media_extern", "<some_other_drive>"]
    

    For example:

    sdb      8:16   1   471M  0 disk 
    └─sdb1   8:17   1   471M  0 part /media/jacob/19C3-0A41
    sdc      8:32   0 698,6G  0 disk 
    └─sdc1   8:33   0 698,6G  0 part /media/jacob/media_extern
    sr0     11:0    1  1024M  0 rom  
    

    In the output of my lsblk, there are two devices: 19C3-0A41 and media_extern. The last one is my permanently connected disk I want to exclude:

    excluded = ["media_extern"]
    

Save the script as copy_flash.py, run it by:

python3 /path/to/copy_flash.py

If it does what you want, add it to your startup applications: Dash > Startup Applications > Add

Share:
20,590

Related videos on Youtube

Eng Fares
Author by

Eng Fares

Updated on September 18, 2022

Comments

  • Eng Fares
    Eng Fares over 1 year

    I want to program my Ubuntu in such a way that it automatically copies the content of USB flash drive to a defined folder in my home directory.

    I would like this to be done automatically when any flash drive is being connected (so not just specific ones).

    • Jacob Vlijm
      Jacob Vlijm over 9 years
      all usb block devices or only flash drives?
    • Jacob Vlijm
      Jacob Vlijm over 9 years
      That seems hardly possible since it seems Ubuntu defines the type of device mainly by the file system; I tested formatting a flash drive as ext4, and it showed up as... a "normal" drive instead of a flash drive. I made a workaround, see my upcoming answer.
    • Eng Fares
      Eng Fares over 9 years
      if it possible on fat then tell me I don't care about ext4 flashs
    • Jacob Vlijm
      Jacob Vlijm over 9 years
      At the moment of your snapshot, no external drive seems to be mounted, I will post an example to my answer.
    • Eng Fares
      Eng Fares over 9 years
      yes they are all unmounted except "sdb2" mounted at "/", I cant't exclude it
    • Jacob Vlijm
      Jacob Vlijm over 9 years
      Nono, you don't have to. Only the usb devices that you want to exclude. The script recognizes if a device is a usb or not. "normal" drives are excluded already.
    • Eng Fares
      Eng Fares over 9 years
      my bad, but it still copying the "/" (computer) content to my directory
    • Jacob Vlijm
      Jacob Vlijm over 9 years
      Really???? that is weird, not your fault. Is it an internal drive?
    • Jacob Vlijm
      Jacob Vlijm over 9 years
      You are welcome, glad it works.
    • Admin
      Admin over 8 years
      Is it possible to modify the above script to only copy jpg and mp4?