Сравнить две машины по инвентарю
Сравнивает два JSON-отчёта и показывает только те поля, которые отличаются.
Что делает скрипт
Скрипт разворачивает вложенные словари в плоские ключи и сравнивает два файла инвентаризации. В отчёте видны ключи только первой машины, только второй и изменённые значения. Для CI есть флаг --fail-on-diff, а результат можно сохранить в JSON.
Быстрый старт
python compare_machines.py first.json second.json
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python compare_machines.py pc-a.json pc-b.jsonpython compare_machines.py pc-a.json pc-b.json --ignore updated_at --fail-on-diffpython compare_machines.py before.json after.json --json diff.json
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
compare_machines.py
#!/usr/bin/env python3
"""Сравнение двух JSON-отчётов об инвентаре."""
from __future__ import annotations
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Iterator
def flatten(value: Any, prefix: str = "") -> Iterator[tuple[str, Any]]:
if isinstance(value, dict):
for key in sorted(value, key=str):
child = f"{prefix}.{key}" if prefix else str(key)
yield from flatten(value[key], child)
elif isinstance(value, list):
for index, item in enumerate(value):
yield from flatten(item, f"{prefix}[{index}]")
else:
yield prefix, value
def load(path: Path) -> dict[str, Any]:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except OSError as error:
raise SystemExit(f"Не удалось прочитать {path}: {error}")
except json.JSONDecodeError as error:
raise SystemExit(f"Некорректный JSON в {path}: {error}")
if not isinstance(data, dict):
raise SystemExit(f"{path}: ожидался объект JSON")
return dict(flatten(data))
def normalize(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
def main() -> int:
parser = argparse.ArgumentParser(description="Сравнить два JSON-отчёта")
parser.add_argument("first", type=Path, help="Первый отчёт")
parser.add_argument("second", type=Path, help="Второй отчёт")
parser.add_argument("--ignore", action="append", default=[], help="Префикс ключа для пропуска")
parser.add_argument("--json", type=Path, help="Сохранить различия в JSON")
parser.add_argument("--fail-on-diff", action="store_true", help="Код 1 при различиях")
args = parser.parse_args()
first = load(args.first)
second = load(args.second)
ignore = tuple(args.ignore)
only_first = []
only_second = []
changed = []
for key in sorted(set(first) | set(second)):
if ignore and key.startswith(ignore):
continue
if key not in second:
only_first.append(key)
elif key not in first:
only_second.append(key)
elif normalize(first[key]) != normalize(second[key]):
changed.append({"key": key, "first": first[key], "second": second[key]})
print(f"Только в {args.first.name}: {len(only_first)}")
for key in only_first:
print(f" + {key}")
print(f"Только в {args.second.name}: {len(only_second)}")
for key in only_second:
print(f" + {key}")
print(f"Отличается: {len(changed)}")
for item in changed:
print(f" ~ {item['key']}: {item['first']!r} -> {item['second']!r}")
if args.json:
args.json.parent.mkdir(parents=True, exist_ok=True)
payload = {
"generated": datetime.now().isoformat(timespec="seconds"),
"first": str(args.first),
"second": str(args.second),
"only_first": only_first,
"only_second": only_second,
"changed": changed,
}
args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8")
print(f"JSON сохранён: {args.json}")
if args.fail_on_diff and (only_first or only_second or changed):
return 1
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except KeyboardInterrupt:
print("Прервано пользователем", file=sys.stderr)
raise SystemExit(130)
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.