54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
"""USB-Block-Devices des Hosts auflisten (via lsblk, /dev + /run/udev gemountet)."""
|
|
import json
|
|
import subprocess
|
|
|
|
|
|
def list_usb_sticks():
|
|
out = subprocess.run(
|
|
["lsblk", "-J", "-b", "-o", "NAME,SIZE,MODEL,VENDOR,TRAN,RM,TYPE,MOUNTPOINT"],
|
|
capture_output=True,
|
|
text=True,
|
|
check=True,
|
|
).stdout
|
|
data = json.loads(out)
|
|
root = get_root_disk_name()
|
|
sticks = []
|
|
for dev in data.get("blockdevices", []):
|
|
if dev.get("type") != "disk":
|
|
continue
|
|
is_removable = str(dev.get("rm")) in ("1", "True", "true")
|
|
is_usb_tran = dev.get("tran") == "usb"
|
|
if not (is_removable or is_usb_tran):
|
|
continue
|
|
name = dev["name"]
|
|
mounted = bool(dev.get("mountpoint")) or any(
|
|
c.get("mountpoint") for c in (dev.get("children") or [])
|
|
)
|
|
sticks.append(
|
|
{
|
|
"name": name,
|
|
"path": f"/dev/{name}",
|
|
"size_bytes": int(dev.get("size") or 0),
|
|
"model": (dev.get("model") or "").strip(),
|
|
"vendor": (dev.get("vendor") or "").strip(),
|
|
"transport": dev.get("tran"),
|
|
"mounted": mounted,
|
|
"is_root_disk": name == root,
|
|
}
|
|
)
|
|
return sticks
|
|
|
|
|
|
def get_root_disk_name():
|
|
"""Name (ohne /dev/) der Platte, auf der / liegt -- fuer Schutz vor Selbstzerstoerung."""
|
|
try:
|
|
src = subprocess.run(
|
|
["findmnt", "-n", "-o", "SOURCE", "/"], capture_output=True, text=True, check=True
|
|
).stdout.strip()
|
|
pk = subprocess.run(
|
|
["lsblk", "-no", "PKNAME", src], capture_output=True, text=True
|
|
).stdout.strip()
|
|
return pk or src.replace("/dev/", "")
|
|
except Exception: # noqa: BLE001
|
|
return None
|