system_info.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """
  2. agent67.tools.system_info — 系统信息查询
  3. Lambda: λ query_json. system_info(query)
  4. """
  5. import json
  6. import platform
  7. import subprocess
  8. def _run(cmd: str) -> str:
  9. try:
  10. r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=10)
  11. return r.stdout.strip()
  12. except Exception:
  13. return "N/A"
  14. def query_system(input_json: str) -> str:
  15. """
  16. 查询系统信息。
  17. 支持: cpu / memory / disk / network / process / battery / all
  18. """
  19. try:
  20. data = json.loads(input_json)
  21. query = data.get("query", "all")
  22. except (json.JSONDecodeError, AttributeError):
  23. query = str(input_json).strip().lower()
  24. is_mac = platform.system() == "Darwin"
  25. sections = []
  26. if query in ("cpu", "all"):
  27. if is_mac:
  28. cpu_info = _run("sysctl -n machdep.cpu.brand_string")
  29. cores = _run("sysctl -n hw.ncpu")
  30. cpu_usage = _run("top -l 1 -n 0 | grep 'CPU usage'")
  31. sections.append(f"🖥️ CPU:\n 型号: {cpu_info}\n 核心数: {cores}\n {cpu_usage}")
  32. else:
  33. sections.append(f"🖥️ CPU:\n {_run('lscpu | head -15')}")
  34. if query in ("memory", "mem", "all"):
  35. if is_mac:
  36. total = _run("sysctl -n hw.memsize")
  37. try:
  38. total_gb = int(total) / (1024 ** 3)
  39. sections.append(f"🧠 内存: {total_gb:.1f} GB")
  40. except ValueError:
  41. sections.append(f"🧠 内存: {total}")
  42. else:
  43. sections.append(f"🧠 内存:\n {_run('free -h')}")
  44. if query in ("disk", "all"):
  45. sections.append(f"💾 磁盘:\n {_run('df -h / | tail -1')}")
  46. if query in ("network", "net", "all"):
  47. ip_info = _run("ifconfig | grep 'inet ' | grep -v 127.0.0.1")
  48. sections.append(f"🌐 网络:\n {ip_info}")
  49. if query in ("process", "proc", "top"):
  50. top_procs = _run("ps aux --sort=-%cpu 2>/dev/null | head -6 || ps aux -r | head -6")
  51. sections.append(f"📊 Top 进程:\n{top_procs}")
  52. if query in ("battery", "bat", "all") and is_mac:
  53. battery = _run("pmset -g batt")
  54. sections.append(f"🔋 电池:\n {battery}")
  55. if not sections:
  56. return f"❌ 未知查询: {query}. 支持: cpu/memory/disk/network/process/battery/all"
  57. return "\n\n".join(sections)