#!/usr/bin/env python3 """Инвентаризация оборудования Linux без серийных номеров.""" from __future__ import annotations import argparse import json import os import shutil import subprocess from pathlib import Path def run(argv: list[str]) -> subprocess.CompletedProcess[str] | None: try: return subprocess.run(argv, capture_output=True, text=True, check=False) except FileNotFoundError: return None def read(path: str) -> str: try: return Path(path).read_text(encoding="utf-8", errors="replace").strip() except OSError: return "" def cpu_info() -> dict: text = Path("/proc/cpuinfo").read_text(encoding="utf-8", errors="replace") model = "неизвестно" logical = 0 pairs = set() physical = None core = None for line in text.splitlines(): if line.startswith("processor"): logical += 1 elif line.lower().startswith("model name") and model == "неизвестно": model = line.split(":", 1)[1].strip() elif line.startswith("physical id"): physical = line.split(":", 1)[1].strip() elif line.startswith("core id"): core = line.split(":", 1)[1].strip() if physical is not None and core is not None: pairs.add((physical, core)) physical = None core = None return {"model": model, "logical": logical, "physical": len(pairs) or logical} def dmi_sections(args: list[str]) -> list[dict]: result = run(["dmidecode", *args]) if result is None or result.returncode != 0: return [] sections = [] current = None for line in result.stdout.splitlines(): if line and not line.startswith(("\t", " ")) and ":" not in line: if current: sections.append(current) current = {"section": line.strip()} elif current is not None and ":" in line: key, value = line.strip().split(":", 1) key = key.strip() if key not in {"Serial Number", "UUID", "SKU Number", "Asset Tag"}: current[key] = value.strip() if current: sections.append(current) return sections def memory_modules(use_dmi: bool) -> list[dict]: if not use_dmi: return [] modules = [] for section in dmi_sections(["-t", "memory"]): if section.get("section") != "Memory Device": continue size = section.get("Size", "") if not size or "No Module Installed" in size: continue modules.append( { "size": size, "speed": section.get("Speed", "-"), "type": section.get("Type", "-"), "manufacturer": section.get("Manufacturer", "-"), "locator": section.get("Locator", "-"), } ) return modules def dmi_summary(use_dmi: bool) -> tuple[dict, dict]: if not use_dmi: return {}, {} system = {} board = {} for section in dmi_sections(["-t", "system"]): if section.get("section") == "System Information": system = section for section in dmi_sections(["-t", "baseboard"]): if section.get("section") == "Baseboard Information": board = section keys = ("Manufacturer", "Product Name", "Version", "Family") return ( {key: system[key] for key in keys if system.get(key)}, {key: board[key] for key in keys if board.get(key)}, ) def pci_devices() -> list[str]: result = run(["lspci", "-nn"]) if result is None or result.returncode != 0: return [] return [line.strip() for line in result.stdout.splitlines() if line.strip()] def usb_devices() -> list[str]: result = run(["lsusb"]) if result is None or result.returncode != 0: return [] return [line.strip() for line in result.stdout.splitlines() if line.strip()] def disks() -> list[dict]: result = run(["lsblk", "-J", "-d", "-o", "NAME,SIZE,MODEL,ROTA,TRAN"]) if result is None or result.returncode != 0: return [] try: data = json.loads(result.stdout) except json.JSONDecodeError: return [] return data.get("blockdevices", []) def battery() -> list[dict]: values = [] for path in sorted(Path("/sys/class/power_supply").glob("BAT*")): values.append( { "name": path.name, "status": read(str(path / "status")) or "unknown", "capacity": read(str(path / "capacity")) or "unknown", "energy_now": read(str(path / "energy_now")), "energy_full": read(str(path / "energy_full")), "power_now": read(str(path / "power_now")), } ) return values def thermal() -> list[dict]: values = [] for path in sorted(Path("/sys/class/thermal").glob("thermal_zone*")): zone_type = read(str(path / "type")) or path.name raw = read(str(path / "temp")) try: temperature = round(int(raw) / 1000.0, 1) except ValueError: temperature = None values.append({"zone": zone_type, "temperature": temperature}) return values def fans() -> list[dict]: values = [] for path in sorted(Path("/sys/class/hwmon").glob("hwmon*/fan*_input")): label = read(str(path.with_name(path.name.replace("_input", "_label")))) or path.name raw = read(str(path)) try: speed = int(raw) except ValueError: speed = None values.append({"name": label, "rpm": speed}) return values def kernel_errors() -> list[str]: result = run(["dmesg", "--level=err,warn"]) if result is None or result.returncode != 0: return [] return [line.strip() for line in result.stdout.splitlines() if line.strip()][-20:] def main() -> int: parser = argparse.ArgumentParser(description="Инвентаризация оборудования Linux") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") parser.add_argument("--no-dmidecode", action="store_true", help="Не вызывать dmidecode") args = parser.parse_args() use_dmi = not args.no_dmidecode if use_dmi and shutil.which("dmidecode") is None: use_dmi = False cpu = cpu_info() system, board = dmi_summary(use_dmi) memory = memory_modules(use_dmi) pci = pci_devices() usb = usb_devices() block = disks() power = battery() temps = thermal() fan_values = fans() errors = kernel_errors() print("== CPU ==") print(f"Модель: {cpu['model']}") print(f"Логических ядер: {cpu['logical']}, физических: {cpu['physical']}") if system or board: print("\n== Система ==") if system: print(f"Производитель: {system.get('Manufacturer', '-')}") print(f"Модель: {system.get('Product Name', '-')}") if board: print(f"Плата: {board.get('Manufacturer', '-')} {board.get('Product Name', '-')}") elif use_dmi: print("\n[INFO] dmidecode не дал данных, возможно нужен root.") if memory: print("\n== Память ==") for module in memory: print(f" {module['size']:<8} {module['speed']:<12} {module['type']:<8} {module['manufacturer']:<18} {module['locator']}") print("\n== PCI ==") print(f"Устройств: {len(pci)}") for line in pci: if any(marker in line for marker in ("VGA compatible", "3D controller", "Display controller", "Ethernet controller", "Network controller")): print(f" {line}") print("\n== USB ==") print(f"Устройств: {len(usb)}") for line in usb[:10]: print(f" {line}") print("\n== Диски ==") for item in block: name = item.get("name", "?") size = item.get("size", "?") model = (item.get("model") or "-").strip() transport = item.get("tran") or "-" rotational = "HDD" if item.get("rota") else "SSD" print(f" /dev/{name:<10} {size:<10} {rotational:<4} {transport:<5} {model}") if power: print("\n== Питание ==") for item in power: print(f" {item['name']}: {item['status']}, {item['capacity']}%") if temps: print("\n== Температуры ==") for item in temps: print(f" {item['zone']}: {item['temperature']} C") if fan_values: print("\n== Вентиляторы ==") for item in fan_values: print(f" {item['name']}: {item['rpm']} RPM") print("\n== dmesg err/warn ==") if errors: for line in errors: print(f" {line}") else: print(" нет данных или нет доступа, запустите от root.") if args.json: args.json.write_text( json.dumps( { "cpu": cpu, "system": system, "baseboard": board, "memory": memory, "pci": pci, "usb": usb, "disks": block, "battery": power, "thermal": temps, "fans": fan_values, "kernel_errors": errors, }, ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) print(f"\nJSON сохранён: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())