Script that detect usb when it is inserted and copy files from usb to computer

2 min read 07-10-2024
Script that detect usb when it is inserted and copy files from usb to computer


Automating File Transfers: Detecting USB Drives and Copying Files

Have you ever found yourself manually copying files from a USB drive to your computer, wishing there was a simpler way? This article will walk you through creating a Python script that automatically detects USB drive insertion and copies files from the drive to your computer.

The Scenario: Streamlining File Transfers

Imagine you regularly receive data on USB drives, but the process of manually plugging in the drive, opening folders, and copying files feels repetitive and time-consuming. This script will automate this process, making file transfers more efficient and less prone to errors.

The Script: Detecting USB Drives and Copying Files

import os
import time
import shutil

def copy_files_from_usb(source_path, destination_path):
    """Copies files from the specified source path (USB drive) to the destination path."""
    for filename in os.listdir(source_path):
        source_file = os.path.join(source_path, filename)
        destination_file = os.path.join(destination_path, filename)
        if os.path.isfile(source_file):
            shutil.copy2(source_file, destination_file)

def detect_usb_drive():
    """Detects USB drive insertion by monitoring changes in drive list."""
    drives = []
    while True:
        current_drives = [drive for drive in os.listdir('/sys/block') if 'sd' in drive]
        if current_drives != drives:
            drives = current_drives
            for drive in drives:
                # Get the mount point for the USB drive
                mount_point = os.popen(f"sudo mount | grep /dev/{drive}").read().split()[2]
                print(f"USB drive detected: {drive}, mounted at: {mount_point}")
                copy_files_from_usb(mount_point, '/path/to/your/destination/folder')
        time.sleep(1)  # Check for changes every second

if __name__ == "__main__":
    detect_usb_drive()

Explanation:

  1. Imports: The script uses os for system interactions, time for delays, and shutil for file copying.
  2. copy_files_from_usb(): This function takes the source path (USB drive) and destination path as arguments and copies all files from the source to the destination, preserving file permissions and timestamps using shutil.copy2.
  3. detect_usb_drive(): This function constantly monitors /sys/block for changes in drive listings. It identifies newly connected USB drives (those with "sd" in their name) and uses the mount command to determine the mount point for the drive. Once the mount point is found, the copy_files_from_usb() function is called to copy files.
  4. Main Execution: The if __name__ == "__main__": block ensures that the detect_usb_drive() function runs only when the script is executed directly, not when imported as a module.

Important Considerations:

  • Permissions: The script requires root access to read the /sys/block directory and to execute the mount command. You might need to run the script as root or using sudo.
  • File Filtering: The script currently copies all files from the USB drive. You can add logic within the copy_files_from_usb() function to selectively copy files based on their extension or other criteria.
  • Error Handling: The script doesn't handle potential errors like drive unmounting during the copying process. Implement appropriate error handling mechanisms to gracefully manage these situations.

Additional Value:

  • Customization: You can modify the destination path to suit your needs and adapt the file filtering logic for specific file types.
  • Cross-Platform: This basic script can be adapted for other operating systems with necessary modifications.

References:

By implementing this script, you can automate file transfer from USB drives, saving time and effort in your daily tasks. Remember to test the script thoroughly and adjust it according to your specific requirements.