system_info.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import os
  2. import platform
  3. import re
  4. import socket
  5. import subprocess
  6. import time
  7. import psutil
  8. def get_network_info():
  9. """Obtiene información de red usando psutil"""
  10. ips = []
  11. try:
  12. net_info = psutil.net_if_addrs()
  13. for interface, addrs in net_info.items():
  14. if interface == "lo":
  15. continue
  16. for addr in addrs:
  17. if addr.family == socket.AF_INET:
  18. ips.append(
  19. {
  20. "interface": interface,
  21. "ip": addr.address,
  22. "netmask": addr.netmask,
  23. "version": "IPv4",
  24. }
  25. )
  26. except Exception as e:
  27. return f"Error: {str(e)}"
  28. return ips if ips else "No disponible"
  29. def get_os_info():
  30. """Obtiene información del sistema operativo de manera confiable"""
  31. try:
  32. with open("/etc/os-release") as f:
  33. os_data = {}
  34. for line in f:
  35. if "=" in line:
  36. key, value = line.strip().split("=", 1)
  37. os_data[key] = value.strip('"')
  38. os_name = os_data.get(
  39. "PRETTY_NAME", os_data.get("NAME", os_data.get("ID", "Linux Desconocido"))
  40. )
  41. return f"{os_name} ({platform.machine()})"
  42. except Exception:
  43. return f"{platform.system()} {platform.release()} ({platform.machine()})"
  44. def get_uptime():
  45. """Obtiene tiempo de actividad del sistema"""
  46. try:
  47. with open("/proc/uptime") as f:
  48. uptime_seconds = float(f.readline().split()[0])
  49. days = int(uptime_seconds // 86400)
  50. hours = int((uptime_seconds % 86400) // 3600)
  51. minutes = int((uptime_seconds % 3600) // 60)
  52. return f"{days}d {hours}h {minutes}m"
  53. except Exception as e:
  54. return f"Error al obtener el tiempo de actividad: {str(e)}"
  55. def get_ram_info():
  56. """Obtiene información de memoria RAM usando psutil"""
  57. try:
  58. ram = psutil.virtual_memory()
  59. return {
  60. "total": f"{ram.total / (1024**3):.2f} GB",
  61. "available": f"{ram.available / (1024**3):.2f} GB",
  62. "used": f"{ram.used / (1024**3):.2f} GB",
  63. "percent": f"{ram.percent}%",
  64. }
  65. except Exception as e:
  66. return f"Error: {str(e)}"
  67. def get_swap_info():
  68. """Obtiene información de memoria swap usando psutil"""
  69. try:
  70. swap = psutil.swap_memory()
  71. if swap.total > 0:
  72. return {
  73. "total": f"{swap.total / (1024**3):.2f} GB",
  74. "used": f"{swap.used / (1024**3):.2f} GB",
  75. "free": f"{swap.free / (1024**3):.2f} GB",
  76. "percent": f"{swap.percent}%",
  77. }
  78. return "No disponible"
  79. except Exception as e:
  80. return f"Error: {str(e)}"
  81. def get_cpu_info():
  82. """Obtiene información de la CPU usando psutil"""
  83. try:
  84. cpu_percent = psutil.cpu_percent(interval=0.5)
  85. try:
  86. cpu_freq = psutil.cpu_freq()
  87. freq_current = cpu_freq.current
  88. freq_min = cpu_freq.min
  89. freq_max = cpu_freq.max
  90. except Exception as e:
  91. freq_current = freq_min = freq_max = "N/A"
  92. print(f"Error al obtener información de frecuencia de CPU: {str(e)}")
  93. cpu_times = psutil.cpu_times_percent(interval=0.5, percpu=False)
  94. return {
  95. "physical_cores": psutil.cpu_count(logical=False),
  96. "total_cores": psutil.cpu_count(logical=True),
  97. "usage": f"{cpu_percent}%",
  98. "current_freq": f"{freq_current} MHz"
  99. if isinstance(freq_current, int | float)
  100. else freq_current,
  101. "min_freq": f"{freq_min} MHz"
  102. if isinstance(freq_min, int | float)
  103. else freq_min,
  104. "max_freq": f"{freq_max} MHz"
  105. if isinstance(freq_max, int | float)
  106. else freq_max,
  107. "user_time": f"{cpu_times.user}%",
  108. "system_time": f"{cpu_times.system}%",
  109. "idle_time": f"{cpu_times.idle}%",
  110. }
  111. except Exception as e:
  112. return f"Error: {str(e)}"
  113. def get_squid_version():
  114. """Obtiene la versión de Squid de manera robusta"""
  115. try:
  116. result = subprocess.run(
  117. ["squid", "-v"],
  118. capture_output=True,
  119. text=True,
  120. timeout=5,
  121. )
  122. output = result.stdout + result.stderr
  123. patterns = [
  124. r"Squid Cache: Version ([\d\.]+[\w\-\.]*)",
  125. r"Version: ([\d\.]+[\w\-\.]*)",
  126. r"squid/([\d\.]+[\w\-\.]*)",
  127. ]
  128. for pattern in patterns:
  129. match = re.search(pattern, output)
  130. if match:
  131. return match.group(1)
  132. return "Instalado (versión no detectada)"
  133. except FileNotFoundError:
  134. return "No instalado"
  135. except Exception as e:
  136. return f"Error: {str(e)}"
  137. # Variables globales para el cálculo de estadísticas de red
  138. _last_net_io = None
  139. _last_net_time = None
  140. def get_network_stats():
  141. """Obtiene estadísticas de uso de red (ancho de banda)"""
  142. global _last_net_io, _last_net_time
  143. try:
  144. current_time = time.time()
  145. current_net_io = psutil.net_io_counters()
  146. # Si es la primera vez, inicializar y esperar 1 segundo
  147. if _last_net_io is None:
  148. _last_net_io = current_net_io
  149. _last_net_time = current_time
  150. time.sleep(1)
  151. current_time = time.time()
  152. current_net_io = psutil.net_io_counters()
  153. # Calcular tiempo transcurrido
  154. time_diff = current_time - _last_net_time
  155. # Calcular bytes por segundo
  156. bytes_sent_per_sec = int(
  157. (current_net_io.bytes_sent - _last_net_io.bytes_sent) / time_diff
  158. )
  159. bytes_recv_per_sec = int(
  160. (current_net_io.bytes_recv - _last_net_io.bytes_recv) / time_diff
  161. )
  162. # Convertir a Mbps
  163. up_mbps = round((bytes_sent_per_sec * 8) / 1_000_000, 2)
  164. down_mbps = round((bytes_recv_per_sec * 8) / 1_000_000, 2)
  165. # Actualizar valores para la próxima medición
  166. _last_net_io = current_net_io
  167. _last_net_time = current_time
  168. return {
  169. "up_mbps": up_mbps,
  170. "down_mbps": down_mbps,
  171. "bytes_sent_per_sec": bytes_sent_per_sec,
  172. "bytes_recv_per_sec": bytes_recv_per_sec,
  173. "bytes_sent_total": current_net_io.bytes_sent,
  174. "bytes_recv_total": current_net_io.bytes_recv,
  175. "packets_sent": current_net_io.packets_sent,
  176. "packets_recv": current_net_io.packets_recv,
  177. }
  178. except Exception as e:
  179. return {
  180. "up_mbps": 0.0,
  181. "down_mbps": 0.0,
  182. "bytes_sent_per_sec": 0,
  183. "bytes_recv_per_sec": 0,
  184. "bytes_sent_total": 0,
  185. "bytes_recv_total": 0,
  186. "packets_sent": 0,
  187. "packets_recv": 0,
  188. "error": str(e),
  189. }
  190. def get_timezone():
  191. try:
  192. if os.path.exists("/etc/timezone"):
  193. with open("/etc/timezone") as f:
  194. return f.read().strip()
  195. tz_path = os.path.realpath("/etc/localtime")
  196. if "zoneinfo" in tz_path:
  197. return tz_path.split("zoneinfo/")[-1]
  198. result = subprocess.run(["timedatectl"], stdout=subprocess.PIPE, text=True)
  199. match = re.search(r"Time zone: (\S+)\s+(\S+/\S+)", result.stdout)
  200. if match:
  201. return f"{match.group(1)} {match.group(2)}"
  202. return "Desconocido"
  203. except Exception as e:
  204. return f"Error al obtener la zona horaria: {str(e)}"