#!/usr/bin/env python3 """Краткий отчёт о системе: ОС, CPU, память, диски и uptime.""" from __future__ import annotations import argparse import ctypes import json import os import platform import shutil import socket import subprocess import sys import time from datetime import timedelta from pathlib import Path def read_text(path: str) -> str: try: return Path(path).read_text(encoding="utf-8", errors="replace") except OSError: return "" def cpu_model() -> str: system = platform.system() if system == "Linux": for line in read_text("/proc/cpuinfo").splitlines(): if line.lower().startswith("model name"): return line.split(":", 1)[1].strip() elif system == "Darwin": result = subprocess.run( ["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True, check=False, ) if result.returncode == 0: return result.stdout.strip() elif system == "Windows": return platform.processor() or os.environ.get("PROCESSOR_IDENTIFIER", "неизвестно") return platform.processor() or "неизвестно" def memory_info() -> tuple[int, int]: system = platform.system() if system == "Linux": values: dict[str, int] = {} for line in read_text("/proc/meminfo").splitlines(): key, _, rest = line.partition(":") try: values[key] = int(rest.strip().split()[0]) * 1024 except (IndexError, ValueError): continue total = values.get("MemTotal", 0) available = values.get("MemAvailable", values.get("MemFree", 0)) return total, available if system == "Darwin": total_result = subprocess.run( ["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, check=False, ) total = int(total_result.stdout.strip()) if total_result.returncode == 0 else 0 vm = subprocess.run(["vm_stat"], capture_output=True, text=True, check=False).stdout page_size = 4096 free_pages = 0 for line in vm.splitlines(): if "page size of" in line: digits = "".join(ch for ch in line.split("page size of", 1)[1] if ch.isdigit()) if digits: page_size = int(digits) if line.startswith("Pages free:"): try: free_pages = int(line.split(":", 1)[1].strip().rstrip(".")) except ValueError: free_pages = 0 return total, free_pages * page_size if system == "Windows": class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("ullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return int(stat.ullTotalPhys), int(stat.ullAvailPhys) return 0, 0 def uptime_seconds() -> float: system = platform.system() if system == "Linux": raw = read_text("/proc/uptime").split() return float(raw[0]) if raw else 0.0 if system == "Darwin": result = subprocess.run( ["sysctl", "-n", "kern.boottime"], capture_output=True, text=True, check=False, ) if result.returncode == 0 and "sec =" in result.stdout: seconds = result.stdout.split("sec =", 1)[1].split(",", 1)[0].strip() try: return max(0.0, time.time() - float(seconds)) except ValueError: return 0.0 if system == "Windows": kernel32 = ctypes.windll.kernel32 kernel32.GetTickCount64.restype = ctypes.c_ulonglong return kernel32.GetTickCount64() / 1000.0 return 0.0 def disk_rows() -> list[dict[str, object]]: rows: list[dict[str, object]] = [] if platform.system() == "Windows": drives = [ f"{letter}:\\" for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if os.path.exists(f"{letter}:\\") ] else: drives = ["/"] for mount in ("/home", "/var", "/tmp"): if os.path.ismount(mount): drives.append(mount) for mount in drives: try: usage = shutil.disk_usage(mount) except OSError: continue rows.append( { "mount": mount, "total_gb": round(usage.total / 1024**3, 1), "used_gb": round(usage.used / 1024**3, 1), "free_gb": round(usage.free / 1024**3, 1), "percent": round(usage.used / usage.total * 100, 1) if usage.total else 0.0, } ) return rows def human_bytes(value: int) -> str: size = float(value) for unit in ("Б", "КБ", "МБ", "ГБ", "ТБ"): if size < 1024 or unit == "ТБ": return f"{size:.1f} {unit}" size /= 1024 return f"{size:.1f} ТБ" def main() -> int: parser = argparse.ArgumentParser(description="Краткий отчёт о системе") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() total, available = memory_info() used = max(0, total - available) uptime = int(uptime_seconds()) data = { "hostname": socket.gethostname(), "os": f"{platform.system()} {platform.release()}", "version": platform.version(), "machine": platform.machine(), "python": platform.python_version(), "cpu_model": cpu_model(), "cpu_count": os.cpu_count() or 0, "memory_total_bytes": total, "memory_available_bytes": available, "memory_used_percent": round(used / total * 100, 1) if total else 0.0, "uptime_seconds": uptime, "disks": disk_rows(), } print(f"Компьютер: {data['hostname']}") print(f"ОС: {data['os']} ({data['machine']})") print(f"CPU: {data['cpu_model']} ({data['cpu_count']} логических ядер)") print(f"Память: {human_bytes(used)} из {human_bytes(total)} ({data['memory_used_percent']}%)") print(f"Uptime: {timedelta(seconds=uptime)}") print("Диски:") for disk in data["disks"]: print( f" {disk['mount']}: {disk['used_gb']} ГБ из {disk['total_gb']} ГБ, " f"свободно {disk['free_gb']} ГБ ({disk['percent']}%)" ) if args.json: args.json.parent.mkdir(parents=True, exist_ok=True) args.json.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"JSON сохранён: {args.json}") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except KeyboardInterrupt: print("Прервано пользователем", file=sys.stderr) raise SystemExit(130)