system_info.py 9.1 KB

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