Score:1

Auto copy from any USB Stick to another directory

vu flag

with the following instruction I have unfortunately my problems: How can I automatically copy the content of a usb (flash) drive to another directory?

I want that any USB stick/USB hard disk, which is connected to my computer, be copied automatically to a specific directory. Since the computer serves as a server, everything should happen by itself. Neither keyboard, mouse or monitor is connected.

If you know a program that can do this, you can of course tell me.

I have modified the script so far to my directories:

#!/usr/bin/env python3

import subprocess
import time
import shutil

#--
target_folder = "/mnt/Sicherungen"
excluded = []
#--

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)

Unfortunately, however, it does not work afterwards and displays the following:

  Traceback (most recent call last):

  File "/home/elias/Documents/copy_flash.py", line 29, in <module>
    valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split("/")[-1] in excluded) == (True, False)]
  File "/home/elias/Documents/copy_flash.py", line 29, in <listcomp>
    valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split("/")[-1] in excluded) == (True, False)]
  File "/home/elias/Documents/copy_flash.py", line 19, in identify
    output = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
  File "/usr/lib/python3.10/subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  file "/usr/lib/python3.10/subprocess.py", line 524, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/bin/bash', '-c', 'find /dev/disk -ls | grep /loop0']' returned non-zero exit status 1.

I am brand new to Linux. I have never done anything like this before. I would be very grateful for some help.

cn flag
ehm. `udev` rule on "insert usb" is far easier. And you can use `rsync` to copy files (and have it ignore duplicates)
Score:0
jp flag

There are two related Bash scripts here that might help and be both easier to modify and, probably, more reliable.

But, your Python script is failing because lsblk returns loop devices that you are trying to grep for in the output of find /dev/disk -ls which doesn't usually contain such devices and therefore the exit status of that will not report 0(success) i.e. this error message:

subprocess.CalledProcessError: Command '['/bin/bash', '-c', 'find /dev/disk -ls | grep /loop0']' returned non-zero exit status 1.

and you haven't provided proper handling for that as your script expects success only.

The solution is to either rewrite your script to handle such case(s) ... Or simply exclude loop devices from the output of lsblk by changing it in the get_mountedlist() function like so:

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

That is changing only lsblk to lsblk -e 7

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.