Ubuntu – How to automatically copy the content of a usb (flash) drive to another directory

automationautorunbackupscriptsusb-drive

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).

Best Answer

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