Search code examples
pythondebian

How to get IDs and paths of external drives in Debian?


I need to create a script that will list the serial numbers (or other unique identifiers) of all external drives (flash drives, SD cards...) and their directory paths. If there is only one flash drive, the output should be something like this: Flash_Driver_2353457673657 - /media/currentusername/FlashDriverName/

This should be the path where I can write or read files. I was able to write a script that gets a list of device serial numbers. To do this, I'm working with files in the /dev directory. But how can I add paths to them?

import os

 def get_external_drive_serial_numbers():
serial_numbers = []  # Create an empty list to store serial numbers

for root, dirs, files in os.walk('/dev'):  # Traverse the file system in /dev
    for filename in files:
        if filename.startswith('sd') and not filename.startswith('sda') and filename.isalpha():  # Check if it's a storage device and not the system disk; we're not interested in partitions either
            device_path = os.path.join(root, filename)  # Form the full device file path
            udev_info = os.popen(f"udevadm info --query=all --name={device_path}").read()  # Get device information using udevadm
            serial_number = None  # Create a variable to store the serial number
            for line in udev_info.split('\n'):  # Split information into lines and iterate through them
                if 'ID_SERIAL=' in line:  # If the line contains ID_SERIAL
                    serial_number = line.split('=')[1]  # Get the value of the serial number
                    break
            if serial_number:
                serial_numbers.append(serial_number)  # Add the serial number to the list

return serial_numbers  # Return the list of serial numbers

if __name__ == "__main__":
external_drive_serials = get_external_drive_serial_numbers()  # Get the list of serial numbers

if external_drive_serials:
    print("Serial numbers of external drives:")
    for serial in external_drive_serials:
        print(serial)  # Print the serial numbers
else:
    print("No external drives are connected.")

As a result, I want to get a list of paths where files can be written or read and unique identifiers for them, so that I can accurately distinguish between different disks.


Solution

  • I did it with subprocess. You can get the path knowing the path to the flash drive partition in the dev/ directory

    import os
    import subprocess
    
    def get_mount_point(device_path):
    command = ["findmnt", "--source", device_path, "--noheadings", "--output", "TARGET"]
    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    
    if result.returncode == 0:
        return result.stdout.strip()
    
    return None
    
    device_path = '/dev/sdb1'
    mount_point = get_mount_point(device_path)
    
    if mount_point:
       print(f"The device is mounted at: {mount_point}")
    else:
       print("The device is not mounted.")