system_info.py 9.2 KB

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