| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281 |
- import os
- import platform
- import re
- import shutil
- import socket
- import subprocess # nosec B404
- import time
- import psutil
- from flask_babel import gettext as _
- from loguru import logger
- # Variables globales para el cálculo de estadísticas de red
- _last_net_io = None
- _last_net_time = None
- def get_network_info():
- ips = []
- try:
- net_info = psutil.net_if_addrs()
- for interface, addrs in net_info.items():
- if interface == "lo":
- continue
- for addr in addrs:
- if addr.family == socket.AF_INET:
- ips.append(
- {
- "interface": interface,
- "ip": addr.address,
- "netmask": addr.netmask,
- "version": "IPv4",
- }
- )
- except Exception:
- logger.exception("Error getting network interfaces")
- return []
- return ips if ips else "Not available"
- def get_os_info():
- try:
- with open("/etc/os-release") as f:
- os_data = {}
- for line in f:
- if "=" in line:
- key, value = line.strip().split("=", 1)
- os_data[key] = value.strip('"')
- os_name = os_data.get(
- "PRETTY_NAME", os_data.get("NAME", os_data.get("ID", "Unknown Linux"))
- )
- return f"{os_name} ({platform.machine()})"
- except Exception:
- return f"{platform.system()} {platform.release()} ({platform.machine()})"
- def get_uptime():
- try:
- boot_time = psutil.boot_time()
- uptime_seconds = time.time() - boot_time
- days = int(uptime_seconds // 86400)
- hours = int((uptime_seconds % 86400) // 3600)
- minutes = int((uptime_seconds % 3600) // 60)
- return f"{days}d {hours}h {minutes}m"
- except Exception:
- logger.exception("Error getting uptime")
- return "Unknown"
- def get_ram_info():
- try:
- ram = psutil.virtual_memory()
- return {
- "total": f"{ram.total / (1024**3):.2f} GB",
- "available": f"{ram.available / (1024**3):.2f} GB",
- "used": f"{ram.used / (1024**3):.2f} GB",
- "percent": f"{ram.percent}%",
- }
- except Exception:
- logger.exception("Error getting RAM info")
- return {}
- def get_swap_info():
- try:
- swap = psutil.swap_memory()
- if swap.total > 0:
- return {
- "total": f"{swap.total / (1024**3):.2f} GB",
- "used": f"{swap.used / (1024**3):.2f} GB",
- "free": f"{swap.free / (1024**3):.2f} GB",
- "percent": f"{swap.percent}%",
- }
- return "Not available"
- except Exception:
- logger.exception("Error getting swap info")
- return "Not available"
- def get_cpu_info():
- try:
- cpu_percent = psutil.cpu_percent(interval=0.5)
- try:
- cpu_freq = psutil.cpu_freq()
- freq_current = cpu_freq.current
- freq_min = cpu_freq.min
- freq_max = cpu_freq.max
- except Exception:
- freq_current = freq_min = freq_max = "N/A"
- logger.exception("Error getting CPU frequency info")
- cpu_times = psutil.cpu_times_percent(interval=0.5, percpu=False)
- return {
- "physical_cores": psutil.cpu_count(logical=False),
- "total_cores": psutil.cpu_count(logical=True),
- "usage": f"{cpu_percent}%",
- "current_freq": f"{freq_current} MHz"
- if isinstance(freq_current, int | float)
- else freq_current,
- "min_freq": f"{freq_min} MHz"
- if isinstance(freq_min, int | float)
- else freq_min,
- "max_freq": f"{freq_max} MHz"
- if isinstance(freq_max, int | float)
- else freq_max,
- "user_time": f"{cpu_times.user}%",
- "system_time": f"{cpu_times.system}%",
- "idle_time": f"{cpu_times.idle}%",
- }
- except Exception:
- logger.exception("Error getting CPU info")
- return {}
- def get_network_stats():
- """Obtiene estadísticas de uso de red (ancho de banda)"""
- global _last_net_io, _last_net_time
- try:
- current_time = time.time()
- current_net_io = psutil.net_io_counters()
- # Si es la primera vez, inicializar y esperar 1 segundo
- if _last_net_io is None:
- _last_net_io = current_net_io
- _last_net_time = current_time
- time.sleep(1)
- current_time = time.time()
- current_net_io = psutil.net_io_counters()
- # Calcular tiempo transcurrido
- time_diff = current_time - _last_net_time
- # Calcular bytes por segundo
- bytes_sent_per_sec = int(
- (current_net_io.bytes_sent - _last_net_io.bytes_sent) / time_diff
- )
- bytes_recv_per_sec = int(
- (current_net_io.bytes_recv - _last_net_io.bytes_recv) / time_diff
- )
- # Convertir a Mbps
- up_mbps = round((bytes_sent_per_sec * 8) / 1_000_000, 2)
- down_mbps = round((bytes_recv_per_sec * 8) / 1_000_000, 2)
- # Actualizar valores para la próxima medición
- _last_net_io = current_net_io
- _last_net_time = current_time
- return {
- "up_mbps": up_mbps,
- "down_mbps": down_mbps,
- "bytes_sent_per_sec": bytes_sent_per_sec,
- "bytes_recv_per_sec": bytes_recv_per_sec,
- "bytes_sent_total": current_net_io.bytes_sent,
- "bytes_recv_total": current_net_io.bytes_recv,
- "packets_sent": current_net_io.packets_sent,
- "packets_recv": current_net_io.packets_recv,
- }
- except Exception:
- logger.exception("Error getting network stats")
- return {
- "up_mbps": 0.0,
- "down_mbps": 0.0,
- "bytes_sent_per_sec": 0,
- "bytes_recv_per_sec": 0,
- "bytes_sent_total": 0,
- "bytes_recv_total": 0,
- "packets_sent": 0,
- "packets_recv": 0,
- "error": _("Internal error"),
- }
- def get_timezone():
- try:
- if os.path.exists("/etc/timezone"):
- with open("/etc/timezone") as f:
- return f.read().strip()
- tz_path = os.path.realpath("/etc/localtime")
- if "zoneinfo" in tz_path:
- return tz_path.split("zoneinfo/")[-1]
- timedatectl_bin = shutil.which("timedatectl")
- if timedatectl_bin:
- result = subprocess.run( # noqa: S603
- [timedatectl_bin], stdout=subprocess.PIPE, text=True
- ) # nosec B603
- match = re.search(r"Time zone: (\S+)\s+(\S+/\S+)", result.stdout)
- if match:
- return f"{match.group(1)} {match.group(2)}"
- return "Unknown"
- except Exception:
- logger.exception("Error getting timezone")
- return "Unknown"
- def get_system_type():
- # Check for Linux
- if os.path.exists("/etc/os-release"):
- try:
- with open("/etc/os-release") as f:
- for line in f:
- if line.startswith("PRETTY_NAME="):
- value = line.split("=", 1)[1].strip()
- if (value.startswith('"') and value.endswith('"')) or (
- value.startswith("'") and value.endswith("'")
- ):
- value = value[1:-1]
- return value
- except Exception as e:
- logger.debug("Error reading /etc/os-release: %s", e)
- # Check for macOS
- sw_vers_bin = shutil.which("sw_vers")
- if sw_vers_bin is not None:
- try:
- result = subprocess.run( # nosec B603 B607 # noqa: S603
- [sw_vers_bin, "-productName"], capture_output=True, text=True, timeout=5
- )
- if result.returncode == 0:
- name = result.stdout.strip()
- result = subprocess.run( # nosec B603 B607 # noqa: S603
- [sw_vers_bin, "-productVersion"],
- capture_output=True,
- text=True,
- timeout=5,
- )
- version = result.stdout.strip()
- return f"{name} {version}"
- except Exception as e:
- logger.debug("Error calling sw_vers: %s", e)
- # Check for Windows
- try:
- result = subprocess.run( # nosec B602 B607 # noqa: S602
- 'systeminfo | findstr /B /C:"OS Name" /B /C:"OS Version"', # noqa: S607
- shell=True,
- capture_output=True,
- text=True,
- timeout=10,
- )
- if result.returncode == 0:
- lines = result.stdout.strip().split("\n")
- os_name = ""
- os_version = ""
- for line in lines:
- if line.startswith("OS Name:"):
- os_name = line.split(":", 1)[1].strip()
- elif line.startswith("OS Version:"):
- os_version = line.split(":", 1)[1].strip()
- if os_name and os_version:
- return f"{os_name} {os_version}"
- elif os_name:
- return os_name
- except Exception as e:
- logger.debug("Error calling systeminfo: %s", e)
- return "Unknown"
|