system_info.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import os
  2. import platform
  3. import re
  4. import socket
  5. import subprocess
  6. import time
  7. import psutil
  8. from loguru import logger
  9. # Variables globales para el cálculo de estadísticas de red
  10. _last_net_io = None
  11. _last_net_time = None
  12. def get_network_info():
  13. ips = []
  14. try:
  15. net_info = psutil.net_if_addrs()
  16. for interface, addrs in net_info.items():
  17. if interface == "lo":
  18. continue
  19. for addr in addrs:
  20. if addr.family == socket.AF_INET:
  21. ips.append(
  22. {
  23. "interface": interface,
  24. "ip": addr.address,
  25. "netmask": addr.netmask,
  26. "version": "IPv4",
  27. }
  28. )
  29. except Exception:
  30. logger.exception("Error getting network interfaces")
  31. return []
  32. return ips if ips else "Not available"
  33. def get_os_info():
  34. try:
  35. with open("/etc/os-release") as f:
  36. os_data = {}
  37. for line in f:
  38. if "=" in line:
  39. key, value = line.strip().split("=", 1)
  40. os_data[key] = value.strip('"')
  41. os_name = os_data.get(
  42. "PRETTY_NAME", os_data.get("NAME", os_data.get("ID", "Unknown Linux"))
  43. )
  44. return f"{os_name} ({platform.machine()})"
  45. except Exception:
  46. return f"{platform.system()} {platform.release()} ({platform.machine()})"
  47. def get_uptime():
  48. try:
  49. boot_time = psutil.boot_time()
  50. uptime_seconds = time.time() - boot_time
  51. days = int(uptime_seconds // 86400)
  52. hours = int((uptime_seconds % 86400) // 3600)
  53. minutes = int((uptime_seconds % 3600) // 60)
  54. return f"{days}d {hours}h {minutes}m"
  55. except Exception:
  56. logger.exception("Error getting uptime")
  57. return "Unknown"
  58. def get_ram_info():
  59. try:
  60. ram = psutil.virtual_memory()
  61. return {
  62. "total": f"{ram.total / (1024**3):.2f} GB",
  63. "available": f"{ram.available / (1024**3):.2f} GB",
  64. "used": f"{ram.used / (1024**3):.2f} GB",
  65. "percent": f"{ram.percent}%",
  66. }
  67. except Exception:
  68. logger.exception("Error getting RAM info")
  69. return {}
  70. def get_swap_info():
  71. try:
  72. swap = psutil.swap_memory()
  73. if swap.total > 0:
  74. return {
  75. "total": f"{swap.total / (1024**3):.2f} GB",
  76. "used": f"{swap.used / (1024**3):.2f} GB",
  77. "free": f"{swap.free / (1024**3):.2f} GB",
  78. "percent": f"{swap.percent}%",
  79. }
  80. return "Not available"
  81. except Exception:
  82. logger.exception("Error getting swap info")
  83. return "Not available"
  84. def get_cpu_info():
  85. try:
  86. cpu_percent = psutil.cpu_percent(interval=0.5)
  87. try:
  88. cpu_freq = psutil.cpu_freq()
  89. freq_current = cpu_freq.current
  90. freq_min = cpu_freq.min
  91. freq_max = cpu_freq.max
  92. except Exception:
  93. freq_current = freq_min = freq_max = "N/A"
  94. logger.exception("Error getting CPU frequency info")
  95. cpu_times = psutil.cpu_times_percent(interval=0.5, percpu=False)
  96. return {
  97. "physical_cores": psutil.cpu_count(logical=False),
  98. "total_cores": psutil.cpu_count(logical=True),
  99. "usage": f"{cpu_percent}%",
  100. "current_freq": f"{freq_current} MHz"
  101. if isinstance(freq_current, int | float)
  102. else freq_current,
  103. "min_freq": f"{freq_min} MHz"
  104. if isinstance(freq_min, int | float)
  105. else freq_min,
  106. "max_freq": f"{freq_max} MHz"
  107. if isinstance(freq_max, int | float)
  108. else freq_max,
  109. "user_time": f"{cpu_times.user}%",
  110. "system_time": f"{cpu_times.system}%",
  111. "idle_time": f"{cpu_times.idle}%",
  112. }
  113. except Exception:
  114. logger.exception("Error getting CPU info")
  115. return {}
  116. def get_network_stats():
  117. """Obtiene estadísticas de uso de red (ancho de banda)"""
  118. global _last_net_io, _last_net_time
  119. try:
  120. current_time = time.time()
  121. current_net_io = psutil.net_io_counters()
  122. # Si es la primera vez, inicializar y esperar 1 segundo
  123. if _last_net_io is None:
  124. _last_net_io = current_net_io
  125. _last_net_time = current_time
  126. time.sleep(1)
  127. current_time = time.time()
  128. current_net_io = psutil.net_io_counters()
  129. # Calcular tiempo transcurrido
  130. time_diff = current_time - _last_net_time
  131. # Calcular bytes por segundo
  132. bytes_sent_per_sec = int(
  133. (current_net_io.bytes_sent - _last_net_io.bytes_sent) / time_diff
  134. )
  135. bytes_recv_per_sec = int(
  136. (current_net_io.bytes_recv - _last_net_io.bytes_recv) / time_diff
  137. )
  138. # Convertir a Mbps
  139. up_mbps = round((bytes_sent_per_sec * 8) / 1_000_000, 2)
  140. down_mbps = round((bytes_recv_per_sec * 8) / 1_000_000, 2)
  141. # Actualizar valores para la próxima medición
  142. _last_net_io = current_net_io
  143. _last_net_time = current_time
  144. return {
  145. "up_mbps": up_mbps,
  146. "down_mbps": down_mbps,
  147. "bytes_sent_per_sec": bytes_sent_per_sec,
  148. "bytes_recv_per_sec": bytes_recv_per_sec,
  149. "bytes_sent_total": current_net_io.bytes_sent,
  150. "bytes_recv_total": current_net_io.bytes_recv,
  151. "packets_sent": current_net_io.packets_sent,
  152. "packets_recv": current_net_io.packets_recv,
  153. }
  154. except Exception:
  155. logger.exception("Error getting network stats")
  156. return {
  157. "up_mbps": 0.0,
  158. "down_mbps": 0.0,
  159. "bytes_sent_per_sec": 0,
  160. "bytes_recv_per_sec": 0,
  161. "bytes_sent_total": 0,
  162. "bytes_recv_total": 0,
  163. "packets_sent": 0,
  164. "packets_recv": 0,
  165. "error": "Internal error",
  166. }
  167. def get_timezone():
  168. try:
  169. if os.path.exists("/etc/timezone"):
  170. with open("/etc/timezone") as f:
  171. return f.read().strip()
  172. tz_path = os.path.realpath("/etc/localtime")
  173. if "zoneinfo" in tz_path:
  174. return tz_path.split("zoneinfo/")[-1]
  175. result = subprocess.run(["timedatectl"], stdout=subprocess.PIPE, text=True)
  176. match = re.search(r"Time zone: (\S+)\s+(\S+/\S+)", result.stdout)
  177. if match:
  178. return f"{match.group(1)} {match.group(2)}"
  179. return "Unknown"
  180. except Exception:
  181. logger.exception("Error getting timezone")
  182. return "Unknown"
  183. def get_system_type():
  184. # Check for Linux
  185. if os.path.exists("/etc/os-release"):
  186. try:
  187. with open("/etc/os-release") as f:
  188. for line in f:
  189. if line.startswith("PRETTY_NAME="):
  190. value = line.split("=", 1)[1].strip()
  191. if (value.startswith('"') and value.endswith('"')) or (
  192. value.startswith("'") and value.endswith("'")
  193. ):
  194. value = value[1:-1]
  195. return value
  196. except Exception:
  197. pass
  198. # Check for macOS
  199. try:
  200. result = subprocess.run(
  201. ["sw_vers", "-productName"], capture_output=True, text=True, timeout=5
  202. )
  203. if result.returncode == 0:
  204. name = result.stdout.strip()
  205. result = subprocess.run(
  206. ["sw_vers", "-productVersion"],
  207. capture_output=True,
  208. text=True,
  209. timeout=5,
  210. )
  211. version = result.stdout.strip()
  212. return f"{name} {version}"
  213. except Exception:
  214. pass
  215. # Check for Windows
  216. try:
  217. result = subprocess.run(
  218. 'systeminfo | findstr /B /C:"OS Name" /B /C:"OS Version"',
  219. shell=True,
  220. capture_output=True,
  221. text=True,
  222. timeout=10,
  223. )
  224. if result.returncode == 0:
  225. lines = result.stdout.strip().split("\n")
  226. os_name = ""
  227. os_version = ""
  228. for line in lines:
  229. if line.startswith("OS Name:"):
  230. os_name = line.split(":", 1)[1].strip()
  231. elif line.startswith("OS Version:"):
  232. os_version = line.split(":", 1)[1].strip()
  233. if os_name and os_version:
  234. return f"{os_name} {os_version}"
  235. elif os_name:
  236. return os_name
  237. except Exception:
  238. pass
  239. return "Unknown"