Files
king bd0c47e6fc feat(asset): add inventory and HWiNFO reports
Requires asset_db initialized with scripts/sql/asset_db_init.sql and ASSET_DB_URL configured before enabling storage.
2026-10-06 02:09:10 +09:00

130 lines
6.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""HWiNFO XML을 부품별로 읽습니다. 외부 파일이나 엔티티는 열지 않습니다."""
from __future__ import annotations
import hashlib
import re
from datetime import datetime
from xml.etree.ElementTree import ParseError
from defusedxml.ElementTree import fromstring
from defusedxml.common import DefusedXmlException
MAX_REPORT_BYTES = 10 * 1024 * 1024
SECTION_LABELS = {
"SYSTEM": "시스템", "CPU": "프로세서", "MOBO": "메인보드 · BIOS",
"MEMORY": "메모리", "VIDEO": "그래픽", "MONITOR": "모니터",
"DRIVES": "저장장치", "NETWORK": "네트워크", "SOUND": "오디오",
"PORTS": "포트 · USB", "BUS": "버스 · 컨트롤러",
}
def _text(node, tag):
return (node.findtext(tag) or "").strip()
def _props(node):
return [{"label": _text(p, "Entry"), "value": _text(p, "Description"),
"type": _text(p, "PropertyType")} for p in node.findall("Property")]
def _pick(nodes, *, types=(), labels=()):
# 언어와 무관한 PropertyType을 먼저 사용하고, 없을 때 한글/영문 항목명을 찾습니다.
properties = [p for n in nodes for p in n["properties"]]
for kind in types:
for p in properties:
if p["type"] == kind and p["value"]:
return p["value"]
for label in labels:
for p in properties:
if p["label"].casefold() == label.casefold() and p["value"]:
return p["value"]
return ""
def parse_hwinfo(raw: bytes) -> dict:
if not raw or len(raw) > MAX_REPORT_BYTES:
raise ValueError("XML 보고서는 비어 있지 않은 10 MB 이하 파일이어야 합니다.")
try:
# HWiNFO의 DTD 선언은 허용하되 파일을 읽지 않습니다. 엔티티는 모두 차단합니다.
root = fromstring(raw, forbid_dtd=False, forbid_entities=True, forbid_external=True)
except (ParseError, DefusedXmlException, ValueError, LookupError) as exc:
raise ValueError("XML을 읽을 수 없습니다. HWiNFO XML 보고서인지 확인하세요.") from exc
if root.tag != "HWINFO" or len(root.findall("COMPUTER")) != 1:
raise ValueError("컴퓨터 한 대의 HWiNFO XML 보고서만 업로드할 수 있습니다.")
computer = root.find("COMPUTER")
sections = [{"key": "SYSTEM", "label": "시스템", "nodes": []}]
count = 0
def walk(node, path, result, depth=0):
nonlocal count
count += 1
if count > 30000 or depth > 64:
raise ValueError("보고서 구조가 너무 크거나 깊습니다.")
name = _text(node, "NodeName")
trail = path + ([name] if name else [])
props = _props(node)
if props:
result.append({"name": name or node.tag, "path": " › ".join(trail), "properties": props})
for child in node:
if child.tag in {"SubNodes", "SubNode"}:
walk(child, trail, result, depth + 1)
elif child.find("NodeName") is not None:
walk(child, trail, result, depth + 1)
sections[0]["nodes"] = [{"name": _text(computer, "NodeName") or "컴퓨터",
"path": "시스템", "properties": _props(computer)}]
subnodes = computer.find("SubNodes")
if subnodes is not None:
for node in subnodes:
group = {"key": node.tag, "label": SECTION_LABELS.get(node.tag, _text(node, "NodeName") or node.tag), "nodes": []}
walk(node, [], group["nodes"])
sections.append(group)
by_key = {s["key"]: s["nodes"] for s in sections}
get = lambda key, **kw: _pick(by_key.get(key, []), **kw)
summary = {
"computer_name": _text(computer, "NodeName") or get("SYSTEM", labels=("컴퓨터 이름", "Computer Name")),
"os": get("SYSTEM", labels=("운영 체제", "Operating System")),
"manufacturer": get("SYSTEM", labels=("컴퓨터 브랜드", "Computer Brand Name")),
"cpu": get("CPU", types=("CPU_NAME",), labels=("프로세서 이름", "Processor Name")),
"cores": get("CPU", labels=("프로세서 코어 수", "CPU 코어 수", "Number of CPU Cores", "Number of Processor Cores")),
"threads": get("CPU", labels=("논리 프로세서 수", "논리 CPU 수", "Number of Logical CPUs", "Number of Logical Processors")),
"motherboard": get("MOBO", types=("SYSTEM_MAINBOARD",)),
"bios": get("MOBO", labels=("BIOS 버전", "BIOS Version")),
"memory": get("MEMORY", labels=("총 메모리 크기", "Total Memory Size")),
"gpu": get("VIDEO", types=("GFXCARD_CHIPSET", "GFXCARD")),
"gpu_memory": get("VIDEO", labels=("그래픽 메모리", "Video Memory", "Video Memory Size")),
"serial": get("MOBO", labels=("제품 일련 번호", "Product Serial Number", "System Serial Number")),
}
if summary["serial"].casefold() in {"system serial number", "to be filled by o.e.m.", "default string", "none", "n/a"}:
summary["serial"] = ""
if not summary["memory"]:
mb = get("MEMORY", types=("SYSTEM_MEMORY",))
if re.fullmatch(r"\d+(\.\d+)?", mb):
summary["memory"] = f"{float(mb) / 1024:g} GiB"
devices = {}
for key, types, labels in [
("DRIVES", ("HDD",), ("드라이브 모델", "Drive Model")),
("MEMORY", (), ("모듈 부품 번호", "Module Part Number")),
("MONITOR", ("MONITOR",), ("모니터 이름", "Monitor Name")),
("NETWORK", ("NETCARD",), ("네트워크 카드", "Network Card")),
("VIDEO", ("GFXCARD_CHIPSET", "GFXCARD"), ("그래픽 프로세서", "Video Chipset")),
]:
devices[key] = []
for node in by_key.get(key, []):
model = _pick([node], types=types, labels=labels)
if model:
devices[key].append({"name": model, "node": node["name"], "properties": node["properties"]})
summary["drive_count"] = len(devices["DRIVES"])
summary["monitor_count"] = len(devices["MONITOR"])
if not summary["computer_name"] or not any(summary[k] for k in ("cpu", "motherboard", "memory", "gpu")):
raise ValueError("컴퓨터 이름과 하드웨어 사양이 포함된 HWiNFO 보고서가 필요합니다.")
scan_time = _text(computer, "ScanTime")
try:
scan_time = datetime.strptime(scan_time, "%d.%m.%Y %H:%M").isoformat(timespec="minutes")
except ValueError:
pass # 날짜 형식이 다르면 원래 보고서에 적힌 시각을 그대로 보존합니다.
warnings = [p["value"] for p in _props(computer) if p["label"] in ("가상 머신 경고", "Virtual Machine Warning") and p["value"]]
return {"summary": summary, "sections": sections, "devices": devices, "scan_time": scan_time,
"warnings": warnings, "sha256": hashlib.sha256(raw).hexdigest(),
"property_count": sum(len(n["properties"]) for s in sections for n in s["nodes"])}