Modularizacion del proyecto mas implementacion
Implementacion de vista a tiempo real de ciertos recursos, Rastrear una ip, Observar las ip de una wifi a tiempo real.
This commit is contained in:
parent
7a465d4c21
commit
e2d3311cd1
|
@ -0,0 +1,107 @@
|
|||
import threading
|
||||
from models.SystemStats import SystemStats
|
||||
from MainView import MainView
|
||||
from models.NetworkingScanner import NetworkScanner
|
||||
import tkinter as tk
|
||||
import time
|
||||
import datetime
|
||||
|
||||
|
||||
class MainController:
|
||||
def __init__(self, view: MainView):
|
||||
self.view = view
|
||||
self.connect_events()
|
||||
self.start_system_updates()
|
||||
|
||||
def connect_events(self):
|
||||
"""Conecta los eventos de la vista con :las funciones del controlador."""
|
||||
self.view.button_track_ip.config(command=self.handle_track_ip)
|
||||
self.view.button_scan_network.config(command=self.start_network_scan_thread)
|
||||
|
||||
def start_network_scan_thread(self):
|
||||
"""Inicia un hilo para escanear la red continuamente cada 5 segundos."""
|
||||
def scan_network_periodically():
|
||||
network_range = NetworkScanner.get_network_range()
|
||||
while True:
|
||||
print("Scanning....")
|
||||
devices = NetworkScanner.scan_network(network_range)
|
||||
self.display_network_scan_results(devices)
|
||||
time.sleep(1) # Escanear cada 5 segundos
|
||||
|
||||
# Inicia un hilo para el escaneo continuo
|
||||
threading.Thread(target=scan_network_periodically, daemon=True).start()
|
||||
|
||||
def handle_track_ip(self):
|
||||
"""Maneja el evento de rastrear una IP."""
|
||||
ip = self.view.entry_ip.get() # Obtener la IP ingresada
|
||||
if not ip:
|
||||
self.view.text_output.insert(tk.END, "Por favor, introduce una IP válida.\n")
|
||||
return
|
||||
|
||||
# Ejecutar fetch_ip_data en un hilo
|
||||
def fetch_ip_data():
|
||||
try:
|
||||
result = SystemStats.track_ip(ip) # Llamar a la función con la IP
|
||||
if "error" in result:
|
||||
self.view.text_output.insert(tk.END, f"Error: {result['error']}\n")
|
||||
else:
|
||||
self.display_ip_data(result)
|
||||
except Exception as e:
|
||||
self.view.text_output.insert(tk.END, f"Error al rastrear la IP: {e}\n")
|
||||
|
||||
threading.Thread(target=fetch_ip_data, daemon=True).start()
|
||||
|
||||
|
||||
def display_network_scan_results(self, devices):
|
||||
"""Muestra los resultados del escaneo en la interfaz."""
|
||||
# Limpiar el texto anterior y mostrar los nuevos resultados
|
||||
self.view.text_network_scan.delete('1.0', tk.END)
|
||||
self.view.text_network_scan.insert(tk.END, "Dispositivos encontrados:\n")
|
||||
for device in devices:
|
||||
self.view.text_network_scan.insert(tk.END, f"IP: {device['ip']}, MAC: {device['mac']}\n")
|
||||
|
||||
def display_ip_data(self, data):
|
||||
"""Muestra la información de la IP en el área de texto."""
|
||||
self.view.text_output.insert(tk.END, f"IP: {data['ip']}\n")
|
||||
self.view.text_output.insert(tk.END, f"Tipo: {data['type']}\n")
|
||||
self.view.text_output.insert(tk.END, f"País: {data['country']} ({data['country_code']})\n")
|
||||
self.view.text_output.insert(tk.END, f"Región: {data['region']} ({data['region_code']})\n")
|
||||
self.view.text_output.insert(tk.END, f"Ciudad: {data['city']}\n")
|
||||
self.view.text_output.insert(tk.END, f"Latitud: {data['latitude']}\n")
|
||||
self.view.text_output.insert(tk.END, f"Longitud: {data['longitude']}\n")
|
||||
self.view.text_output.insert(tk.END, f"Mapa: https://www.google.com/maps/@{data['latitude']},{data['longitude']},8z\n")
|
||||
self.view.text_output.insert(tk.END, "=============================================\n")
|
||||
|
||||
def start_system_updates(self):
|
||||
"""Inicia las actualizaciones periódicas del sistema."""
|
||||
threading.Thread(target=self.update_system_stats, daemon=True).start()
|
||||
self.update_time()
|
||||
|
||||
def update_time(self):
|
||||
"""Actualiza el reloj en la barra de estado."""
|
||||
now = datetime.datetime.now()
|
||||
time_str = now.strftime("%H:%M:%S")
|
||||
date_str = now.strftime("%Y-%m-%d")
|
||||
day_of_week = now.strftime("%A")
|
||||
self.view.label_fecha_hora.config(text=f"{day_of_week}, {date_str} - {time_str}")
|
||||
self.view.root.after(1000, self.update_time) # Actualizar cada segundo
|
||||
|
||||
def update_system_stats(self):
|
||||
"""Actualiza las estadísticas del sistema periódicamente en un hilo."""
|
||||
while True:
|
||||
# Obtener estadísticas del sistema
|
||||
cpu_usage = SystemStats.get_cpu_usage()
|
||||
memory_usage = SystemStats.get_memory_usage()
|
||||
bytes_sent, bytes_recv = SystemStats.get_network_usage()
|
||||
|
||||
# Actualizar etiquetas en el hilo principal
|
||||
self.view.root.after(0, self.view.label_cpu.config, {"text": f"Uso CPU: {cpu_usage:.2f}%"})
|
||||
self.view.root.after(0, self.view.label_uso_memoria.config, {"text": f"Uso RAM: {memory_usage:.2f}%"})
|
||||
self.view.root.after(0, self.view.label_bytes_sent.config, {"text": f"Subida: {bytes_sent / 1024:.2f} KB/s"})
|
||||
self.view.root.after(0, self.view.label_bytes_recv.config, {"text": f"Descarga: {bytes_recv / 1024:.2f} KB/s"})
|
||||
|
||||
time.sleep(1) # Esperar 1 segundo antes de actualizar nuevamente
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
import tkinter as tk # Importar Tkinter para la interfaz gráfica
|
||||
from tkinter import ttk, scrolledtext # Importar widgets específicos de Tkinter
|
||||
|
||||
|
||||
class MainView:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self.root.title("Ventana Responsive")
|
||||
self.root.geometry("1000x700") # Tamaño inicial
|
||||
|
||||
# Configuración de la ventana principal
|
||||
self.root.columnconfigure(1, weight=1) # Columna central ajustable
|
||||
self.root.rowconfigure(0, weight=1) # Fila principal ajustable
|
||||
self.root.rowconfigure(1, weight=0) # Fila inferior (barra de estado)
|
||||
|
||||
# Crear frames principales
|
||||
self.frame_left = tk.Frame(self.root, bg="lightblue", width=200)
|
||||
self.frame_center = tk.Frame(self.root, bg="white", height=400, width=600)
|
||||
self.frame_bottom = tk.Frame(self.root, bg="lightgray", height=50)
|
||||
self.frame_right = tk.Frame(self.root, bg="red", width=200)
|
||||
|
||||
# Configurar posiciones en el grid
|
||||
self.frame_left.grid(row=0, column=0, sticky="ns")
|
||||
self.frame_center.grid(row=0, column=1, padx=10, pady=10, sticky="nsew")
|
||||
self.frame_right.grid(row=0, column=2, sticky="ns")
|
||||
self.frame_bottom.grid(row=1, column=0, columnspan=3, sticky="ew")
|
||||
|
||||
# Configurar tamaños fijos
|
||||
self.frame_left.grid_propagate(False)
|
||||
self.frame_center.grid_propagate(False)
|
||||
self.frame_bottom.grid_propagate(False)
|
||||
self.frame_right.grid_propagate(False)
|
||||
|
||||
# Crear el notebook dentro del frame central
|
||||
self.create_tabs()
|
||||
|
||||
# Crear barra de estado en el frame inferior
|
||||
self.create_status_bar()
|
||||
|
||||
def create_tabs(self):
|
||||
"""Crea las solapas dentro del notebook."""
|
||||
self.notebook = ttk.Notebook(self.frame_center, height=800, width=800)
|
||||
self.notebook.pack(padx=10, pady=10)
|
||||
|
||||
# Solapa 1: IP Tracker
|
||||
tab1 = ttk.Frame(self.notebook)
|
||||
self.notebook.add(tab1, text="IP Tracker")
|
||||
self.create_tracker_ui(tab1)
|
||||
|
||||
# Solapa 2: Escaneo de red
|
||||
tab2 = ttk.Frame(self.notebook)
|
||||
self.notebook.add(tab2, text="Escaneo de Red")
|
||||
self.create_network_scan_ui(tab2)
|
||||
|
||||
# Solapas 3-5: Vacías
|
||||
for i in range(3, 6):
|
||||
tab = ttk.Frame(self.notebook)
|
||||
self.notebook.add(tab, text=f"Solapa {i}")
|
||||
label = ttk.Label(tab, text=f"Contenido de la Solapa {i}")
|
||||
label.pack(pady=10)
|
||||
|
||||
def create_tracker_ui(self, tab):
|
||||
"""Crea la interfaz de usuario para el rastreador de IP en la solapa 1."""
|
||||
label_ip = ttk.Label(tab, text="Introduce la IP para rastrear:")
|
||||
label_ip.pack(pady=5)
|
||||
|
||||
self.entry_ip = ttk.Entry(tab, width=40)
|
||||
self.entry_ip.pack(pady=5)
|
||||
|
||||
self.text_output = scrolledtext.ScrolledText(tab, wrap=tk.WORD, height=10, width=60)
|
||||
self.text_output.pack(fill="both", expand=True, pady=10)
|
||||
|
||||
self.button_track_ip = ttk.Button(tab, text="Rastrear IP")
|
||||
self.button_track_ip.pack(pady=5)
|
||||
|
||||
def create_network_scan_ui(self, tab):
|
||||
"""Crea la interfaz de usuario para el escaneo de red en la Solapa 2."""
|
||||
label = ttk.Label(tab, text="Escaneo de dispositivos en la red:")
|
||||
label.pack(pady=5)
|
||||
|
||||
self.text_network_scan = scrolledtext.ScrolledText(tab, wrap=tk.WORD, height=20, width=80)
|
||||
self.text_network_scan.pack(fill="both", expand=True, pady=10)
|
||||
|
||||
# Botón para iniciar el escaneo
|
||||
self.button_scan_network = ttk.Button(tab, text="Iniciar Escaneo")
|
||||
self.button_scan_network.pack(pady=5)
|
||||
|
||||
def create_status_bar(self):
|
||||
"""Crea una barra de estado en la parte inferior."""
|
||||
self.label_cpu = tk.Label(self.frame_bottom, text="Uso CPU: 0%", bg="orange", anchor="w", width=20)
|
||||
self.label_bytes_recv = tk.Label(self.frame_bottom, text="Descarga: 0 KB/s", bg="blue", anchor="w", width=20)
|
||||
self.label_bytes_sent = tk.Label(self.frame_bottom, text="Subida: 0 KB/s", bg="cyan", anchor="w", width=20)
|
||||
self.label_uso_memoria = tk.Label(self.frame_bottom, text="Uso RAM: 0%", bg="pink", anchor="w", width=20)
|
||||
self.label_fecha_hora = tk.Label(
|
||||
self.frame_bottom, text="Hilo fecha-hora", font=("Helvetica", 14), fg="blue", relief="sunken", anchor="w", width=20
|
||||
)
|
||||
|
||||
self.label_cpu.pack(side="left", fill="x", expand=True)
|
||||
self.label_bytes_recv.pack(side="left", fill="x", expand=True)
|
||||
self.label_bytes_sent.pack(side="left", fill="x", expand=True)
|
||||
self.label_uso_memoria.pack(side="left", fill="x", expand=True)
|
||||
self.label_fecha_hora.pack(side="right", fill="x", expand=True)
|
Binary file not shown.
Binary file not shown.
156
main.py
156
main.py
|
@ -1,153 +1,9 @@
|
|||
import tkinter as tk
|
||||
from tkinter import Menu # Importar el widget Menu
|
||||
from tkinter import ttk # Importar el widget ttk
|
||||
import threading
|
||||
import time
|
||||
import datetime
|
||||
import psutil
|
||||
import tkinter as tk # Importar Tkinter para la interfaz gráfica
|
||||
from MainView import MainView # Importar la clase de la vista
|
||||
from MainController import MainController # Importar la clase del controlador
|
||||
|
||||
def update_memoria(interval):
|
||||
while True:
|
||||
# Obtener el porcentaje de memoria usada
|
||||
memory_usage = psutil.virtual_memory().percent
|
||||
laber_text = "Uso RAM: " +f"{memory_usage:.2f}%";
|
||||
label_uso_memoria.after(1000,interval.config, {"text": laber_text})
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def update_time(status_bar):
|
||||
"""Función que actualiza la hora y el día de la semana en un label"""
|
||||
while True:
|
||||
# Obtener la fecha y hora actual
|
||||
now = datetime.datetime.now()
|
||||
day_of_week = now.strftime("%A") # Día de la semana
|
||||
time_str = now.strftime("%H:%M:%S") # Hora en formato HH:MM:SS
|
||||
date_str = now.strftime("%Y-%m-%d") # Fecha en formato YYYY-MM-DD
|
||||
label_text = f"{day_of_week}, {date_str} - {time_str}"
|
||||
|
||||
# Actualizar el label (debemos usar `after` para asegurarnos que se actualice en el hilo principal de Tkinter)
|
||||
label_fecha_hora.after(1000, status_bar.config, {"text": label_text})
|
||||
|
||||
# Espera 1 segundo antes de actualizar de nuevo
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
# Crear la ventana principal
|
||||
if __name__ == "__main__":
|
||||
root = tk.Tk()
|
||||
root.title("Ventana Responsive")
|
||||
root.geometry("1000x700") # Tamaño inicial
|
||||
|
||||
# Configurar la ventana principal para que sea responsive
|
||||
root.columnconfigure(0, weight=0) # Columna izquierda, tamaño fijo
|
||||
root.columnconfigure(1, weight=1) # Columna central, tamaño variable
|
||||
root.columnconfigure(2, weight=0) # Columna derecha, tamaño fijo
|
||||
root.rowconfigure(0, weight=1) # Fila principal, tamaño variable
|
||||
root.rowconfigure(1, weight=0) # Barra de estado, tamaño fijo
|
||||
|
||||
# Crear el menú superior
|
||||
menu_bar = Menu(root)
|
||||
|
||||
file_menu = Menu(menu_bar, tearoff=0)
|
||||
file_menu.add_command(label="Nuevo")
|
||||
file_menu.add_command(label="Abrir")
|
||||
file_menu.add_separator()
|
||||
file_menu.add_command(label="Salir", command=root.quit)
|
||||
|
||||
edit_menu = Menu(menu_bar, tearoff=0)
|
||||
edit_menu.add_command(label="Copiar")
|
||||
edit_menu.add_command(label="Pegar")
|
||||
|
||||
help_menu = Menu(menu_bar, tearoff=0)
|
||||
help_menu.add_command(label="Acerca de")
|
||||
|
||||
menu_bar.add_cascade(label="Archivo", menu=file_menu)
|
||||
menu_bar.add_cascade(label="Editar", menu=edit_menu)
|
||||
menu_bar.add_cascade(label="Ayuda", menu=help_menu)
|
||||
|
||||
root.config(menu=menu_bar)
|
||||
|
||||
# Crear los frames laterales y el central
|
||||
frame_izquierdo = tk.Frame(root, bg="lightblue", width=200)
|
||||
frame_central = tk.Frame(root, bg="white")
|
||||
frame_derecho = tk.Frame(root, bg="lightgreen", width=200)
|
||||
|
||||
# Colocar los frames laterales y el central
|
||||
frame_izquierdo.grid(row=0, column=0, sticky="ns")
|
||||
frame_central.grid(row=0, column=1, sticky="nsew")
|
||||
frame_derecho.grid(row=0, column=2, sticky="ns")
|
||||
|
||||
# Configurar los tamaños fijos de los frames laterales
|
||||
frame_izquierdo.grid_propagate(False)
|
||||
frame_derecho.grid_propagate(False)
|
||||
|
||||
# Dividir el frame central en dos partes (superior variable e inferior fija)
|
||||
frame_central.rowconfigure(0, weight=1) # Parte superior, tamaño variable
|
||||
frame_central.rowconfigure(1, weight=0) # Parte inferior, tamaño fijo
|
||||
frame_central.columnconfigure(0, weight=1) # Ocupa toda la anchura
|
||||
|
||||
# Crear subframes dentro del frame central
|
||||
frame_superior = tk.Frame(frame_central, bg="lightyellow")
|
||||
frame_inferior = tk.Frame(frame_central, bg="lightgray", height=100)
|
||||
|
||||
# Colocar los subframes dentro del frame central
|
||||
frame_superior.grid(row=0, column=0, sticky="nsew")
|
||||
frame_inferior.grid(row=1, column=0, sticky="ew")
|
||||
|
||||
# Fijar el tamaño de la parte inferior
|
||||
frame_inferior.grid_propagate(False)
|
||||
|
||||
# Crear la barra de estado
|
||||
barra_estado = tk.Label(root, text="Barra de estado", bg="lightgray", anchor="w")
|
||||
barra_estado.grid(row=1, column=0, columnspan=3, sticky="ew")
|
||||
|
||||
# Notebook para las pestañas
|
||||
|
||||
style = ttk.Style()
|
||||
style.configure("CustomNotebook.TNotebook.Tab", font=("Arial", 12, "bold"))
|
||||
notebook = ttk.Notebook(frame_superior, style="CustomNotebook.TNotebook")
|
||||
notebook.pack(fill="both", expand=True)
|
||||
|
||||
|
||||
# Crear cinco solapas
|
||||
for i in range(1, 6):
|
||||
tab = ttk.Frame(notebook)
|
||||
|
||||
notebook.add(tab, text=f"Solapa {i}", padding=4)
|
||||
# Añadir un Label en cada solapa para diferenciarla
|
||||
label = ttk.Label(tab, text=f"Contenido de la Solapa {i}")
|
||||
label.pack(pady=10)
|
||||
|
||||
# Barra de estado
|
||||
# Dividir la barra de estado en 4 labels
|
||||
|
||||
|
||||
# Usar pack para alinear los labels horizontalmente
|
||||
|
||||
|
||||
label_1 = tk.Label(barra_estado, text="Estado 1", bg="green", anchor="w", width=20)
|
||||
label_2 = tk.Label(barra_estado, text="Estado 2", bg="blue", anchor="w", width=20)
|
||||
label_3 = tk.Label(barra_estado, text="Estado 3", bg="cyan", anchor="w", width=20)
|
||||
label_uso_memoria = tk.Label(barra_estado, text="Estado 4", bg="pink", anchor="w", width=20)
|
||||
label_fecha_hora = tk.Label(barra_estado, text="Hilo fecha-hora", font=("Helvetica", 14), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
|
||||
|
||||
label_1.pack(side="left", fill="x", expand=True)
|
||||
label_2.pack(side="left", fill="x", expand=True)
|
||||
label_3.pack(side="left", fill="x", expand=True)
|
||||
label_uso_memoria.pack(side="left", fill="x", expand=True)
|
||||
label_fecha_hora.pack(side="right", fill="x", expand=True)
|
||||
# barra_estado.grid(row=1, column=0, columnspan=3, sticky="ew")
|
||||
|
||||
|
||||
update_thread = threading.Thread(target=update_time, args=(label_fecha_hora,))
|
||||
update_thread.daemon = True # Hacemos el hilo un demonio para que termine con la app
|
||||
update_thread.start()
|
||||
|
||||
update_thread_memoria = threading.Thread(target=update_memoria, args=(label_uso_memoria,))
|
||||
update_thread_memoria.daemon = True
|
||||
update_thread_memoria.start()
|
||||
|
||||
#Uso en memoria
|
||||
|
||||
|
||||
# Ejecución de la aplicación
|
||||
view = MainView(root)
|
||||
controller = MainController(view)
|
||||
root.mainloop()
|
|
@ -0,0 +1,25 @@
|
|||
import socket
|
||||
import ipaddress
|
||||
import nmap
|
||||
|
||||
class NetworkScanner:
|
||||
@staticmethod
|
||||
def get_network_range():
|
||||
"""Obtiene el rango de red basado en la IP local."""
|
||||
hostname = socket.gethostname()
|
||||
local_ip = socket.gethostbyname(hostname)
|
||||
network = ipaddress.ip_network(f"{local_ip}/24", strict=False)
|
||||
print(str(network))
|
||||
return str(network)
|
||||
|
||||
@staticmethod
|
||||
def scan_network(ip_range):
|
||||
"""Realiza un escaneo de red y devuelve los dispositivos detectados."""
|
||||
nm = nmap.PortScanner()
|
||||
nm.scan(hosts=ip_range, arguments='-sn')
|
||||
devices = []
|
||||
for host in nm.all_hosts():
|
||||
if nm[host].state() == "up":
|
||||
mac = nm[host]['addresses'].get('mac', 'No MAC address found')
|
||||
devices.append({'ip': nm[host]['addresses']['ipv4'], 'mac': mac})
|
||||
return devices
|
|
@ -0,0 +1,39 @@
|
|||
import psutil
|
||||
import time
|
||||
import requests
|
||||
|
||||
class SystemStats:
|
||||
@staticmethod
|
||||
def get_memory_usage():
|
||||
"""Obtiene el porcentaje de uso de memoria."""
|
||||
return psutil.virtual_memory().percent
|
||||
|
||||
@staticmethod
|
||||
def get_cpu_usage():
|
||||
"""Obtiene el porcentaje de uso de CPU."""
|
||||
return psutil.cpu_percent(interval=0)
|
||||
|
||||
@staticmethod
|
||||
def get_network_usage():
|
||||
"""Calcula la velocidad de subida y bajada de la red."""
|
||||
net_io_start = psutil.net_io_counters()
|
||||
time.sleep(1) # Esperar 1 segundo para medir el uso
|
||||
net_io_end = psutil.net_io_counters()
|
||||
|
||||
# Calcular velocidades
|
||||
bytes_sent_per_sec = net_io_end.bytes_sent - net_io_start.bytes_sent
|
||||
bytes_recv_per_sec = net_io_end.bytes_recv - net_io_start.bytes_recv
|
||||
|
||||
return bytes_sent_per_sec, bytes_recv_per_sec
|
||||
|
||||
@staticmethod
|
||||
def track_ip(ip):
|
||||
"""Obtiene información de una IP mediante la API ipwho.is."""
|
||||
try:
|
||||
response = requests.get(f"http://ipwho.is/{ip}")
|
||||
data = response.json()
|
||||
if not data.get("success", False):
|
||||
return {"error": data.get("message", "No se encontró información.")}
|
||||
return data
|
||||
except requests.exceptions.RequestException as e:
|
||||
return {"error": str(e)}
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,158 @@
|
|||
import tkinter as tk
|
||||
from tkinter import Menu
|
||||
from tkinter import ttk
|
||||
import threading
|
||||
import psutil
|
||||
import datetime
|
||||
import time
|
||||
|
||||
|
||||
def update_bot_regions_thread(label_memory, label_sent, label_recv, label_cpu):
|
||||
"""Hilo que actualiza las estadísticas del sistema."""
|
||||
while True:
|
||||
# Obtener estadísticas del sistema
|
||||
memory_usage = psutil.virtual_memory().percent
|
||||
bytes_sent_per_sec, bytes_recv_per_sec = get_network_usage()
|
||||
cpu_usage = psutil.cpu_percent(interval=0)
|
||||
|
||||
# Actualizar etiquetas en el hilo principal usando `after`
|
||||
root.after(0, label_memory.config, {"text": f"Uso RAM: {memory_usage:.2f}%"})
|
||||
root.after(0, label_sent.config, {"text": f"Subida: {bytes_sent_per_sec / 1024:.2f} KB/s"})
|
||||
root.after(0, label_recv.config, {"text": f"Descarga: {bytes_recv_per_sec / 1024:.2f} KB/s"})
|
||||
root.after(0, label_cpu.config, {"text": f"Uso CPU: {cpu_usage:.2f}%"})
|
||||
|
||||
time.sleep(1) # Esperar 1 segundo antes de la próxima actualización
|
||||
|
||||
|
||||
def get_network_usage():
|
||||
"""Calcula la velocidad de subida y bajada de la red."""
|
||||
net_io_start = psutil.net_io_counters()
|
||||
time.sleep(1) # Esperar 1 segundo para medir el uso
|
||||
net_io_end = psutil.net_io_counters()
|
||||
|
||||
# Calcular velocidades
|
||||
bytes_sent_per_sec = net_io_end.bytes_sent - net_io_start.bytes_sent
|
||||
bytes_recv_per_sec = net_io_end.bytes_recv - net_io_start.bytes_recv
|
||||
|
||||
return bytes_sent_per_sec, bytes_recv_per_sec
|
||||
|
||||
|
||||
def update_time(label_fecha_hora):
|
||||
"""Actualiza la hora y el día de la semana en un label."""
|
||||
# Obtener la fecha y hora actual
|
||||
now = datetime.datetime.now()
|
||||
day_of_week = now.strftime("%A") # Día de la semana
|
||||
time_str = now.strftime("%H:%M:%S") # Hora en formato HH:MM:SS
|
||||
date_str = now.strftime("%Y-%m-%d") # Fecha en formato YYYY-MM-DD
|
||||
label_text = f"{day_of_week}, {date_str} - {time_str}"
|
||||
|
||||
# Actualizar el label
|
||||
label_fecha_hora.config(text=label_text)
|
||||
|
||||
# Programar la próxima actualización después de 1 segundo
|
||||
root.after(1000, update_time, label_fecha_hora)
|
||||
|
||||
|
||||
# Crear la ventana principal
|
||||
root = tk.Tk()
|
||||
root.title("Ventana Responsive")
|
||||
root.geometry("1000x700") # Tamaño inicial
|
||||
|
||||
# Configurar la ventana principal para que sea responsive
|
||||
root.columnconfigure(0, weight=0) # Columna izquierda, tamaño fijo
|
||||
root.columnconfigure(1, weight=1) # Columna central, tamaño variable
|
||||
root.columnconfigure(2, weight=0) # Columna derecha, tamaño fijo
|
||||
root.rowconfigure(0, weight=1) # Fila principal, tamaño variable
|
||||
root.rowconfigure(1, weight=0) # Barra de estado, tamaño fijo
|
||||
|
||||
|
||||
# Crear el menú superior
|
||||
menu_bar = Menu(root)
|
||||
|
||||
file_menu = Menu(menu_bar, tearoff=0)
|
||||
file_menu.add_command(label="Nuevo")
|
||||
file_menu.add_command(label="Abrir")
|
||||
file_menu.add_separator()
|
||||
file_menu.add_command(label="Salir", command=root.quit)
|
||||
|
||||
edit_menu = Menu(menu_bar, tearoff=0)
|
||||
edit_menu.add_command(label="Copiar")
|
||||
edit_menu.add_command(label="Pegar")
|
||||
|
||||
help_menu = Menu(menu_bar, tearoff=0)
|
||||
help_menu.add_command(label="Acerca de")
|
||||
|
||||
menu_bar.add_cascade(label="Archivo", menu=file_menu)
|
||||
menu_bar.add_cascade(label="Editar", menu=edit_menu)
|
||||
menu_bar.add_cascade(label="Ayuda", menu=help_menu)
|
||||
|
||||
root.config(menu=menu_bar)
|
||||
|
||||
# Crear frames
|
||||
frame_izquierdo = tk.Frame(root, bg="lightblue", width=200)
|
||||
frame_central = tk.Frame(root, bg="white")
|
||||
frame_derecho = tk.Frame(root, bg="lightgreen", width=200)
|
||||
|
||||
frame_izquierdo.grid(row=0, column=0, sticky="ns")
|
||||
frame_central.grid(row=0, column=1, sticky="nsew")
|
||||
frame_derecho.grid(row=0, column=2, sticky="ns")
|
||||
|
||||
frame_izquierdo.grid_propagate(False)
|
||||
frame_derecho.grid_propagate(False)
|
||||
|
||||
|
||||
# Dividir el frame central en dos partes (superior variable e inferior fija)
|
||||
frame_central.rowconfigure(0, weight=1) # Parte superior, tamaño variable
|
||||
frame_central.rowconfigure(1, weight=0) # Parte inferior, tamaño fijo
|
||||
frame_central.columnconfigure(0, weight=1) # Ocupa toda la anchura
|
||||
|
||||
# Crear subframes dentro del frame central
|
||||
frame_superior = tk.Frame(frame_central, bg="lightyellow")
|
||||
frame_inferior = tk.Frame(frame_central, bg="lightgray", height=100)
|
||||
|
||||
# Colocar los subframes dentro del frame central
|
||||
frame_superior.grid(row=0, column=0, sticky="nsew")
|
||||
frame_inferior.grid(row=1, column=0, sticky="ew")
|
||||
|
||||
# Fijar el tamaño de la parte inferior
|
||||
frame_inferior.grid_propagate(False)
|
||||
# Crear la barra de estado
|
||||
barra_estado = tk.Label(root, text="Barra de estado", bg="lightgray", anchor="w")
|
||||
barra_estado.grid(row=1, column=0, columnspan=3, sticky="ew")
|
||||
|
||||
|
||||
# Notebook para las pestañas
|
||||
|
||||
style = ttk.Style()
|
||||
style.configure("CustomNotebook.TNotebook.Tab", font=("Arial", 12, "bold"))
|
||||
notebook = ttk.Notebook(frame_superior, style="CustomNotebook.TNotebook")
|
||||
notebook.pack(fill="both", expand=True)
|
||||
|
||||
|
||||
# Crear cinco solapas
|
||||
for i in range(1, 6):
|
||||
tab = ttk.Frame(notebook)
|
||||
|
||||
notebook.add(tab, text=f"Solapa {i}", padding=4)
|
||||
# Añadir un Label en cada solapa para diferenciarla
|
||||
label = ttk.Label(tab, text=f"Contenido de la Solapa {i}")
|
||||
label.pack(pady=10)
|
||||
|
||||
label_cpu = tk.Label(barra_estado, text="Uso CPU", bg="orange", anchor="w", width=20)
|
||||
label_bytes_recv = tk.Label(barra_estado, text="Descarga", bg="blue", anchor="w", width=20)
|
||||
label_bytes_sent = tk.Label(barra_estado, text="Subida", bg="cyan", anchor="w", width=20)
|
||||
label_uso_memoria = tk.Label(barra_estado, text="Uso RAM", bg="pink", anchor="w", width=20)
|
||||
label_fecha_hora = tk.Label(barra_estado, text="Hilo fecha-hora", font=("Helvetica", 14), fg="blue", relief="sunken", anchor="w", width=20)
|
||||
|
||||
label_cpu.pack(side="left", fill="x", expand=True)
|
||||
label_bytes_recv.pack(side="left", fill="x", expand=True)
|
||||
label_bytes_sent.pack(side="left", fill="x", expand=True)
|
||||
label_uso_memoria.pack(side="left", fill="x", expand=True)
|
||||
label_fecha_hora.pack(side="right", fill="x", expand=True)
|
||||
|
||||
# Iniciar actualizaciones en hilos separados
|
||||
threading.Thread(target=update_bot_regions_thread, args=(label_uso_memoria, label_bytes_sent, label_bytes_recv, label_cpu), daemon=True).start()
|
||||
update_time(label_fecha_hora)
|
||||
|
||||
# Ejecutar la aplicación
|
||||
root.mainloop()
|
46
pruebas.py
46
pruebas.py
|
@ -1,22 +1,32 @@
|
|||
import psutil
|
||||
import socket
|
||||
import ipaddress
|
||||
import nmap
|
||||
import time
|
||||
import threading
|
||||
|
||||
def print_memory_usage(interval=5):
|
||||
"""
|
||||
Imprime el uso de memoria RAM cada 'interval' segundos.
|
||||
def get_network_range():
|
||||
# Obtener la IP local
|
||||
hostname = socket.gethostname()
|
||||
local_ip = socket.gethostbyname(hostname)
|
||||
# Suponemos una máscara de red /24
|
||||
network = ipaddress.ip_network(f"{local_ip}/24", strict=False)
|
||||
return str(network)
|
||||
|
||||
Args:
|
||||
interval (int): Intervalo de tiempo entre cada impresión (en segundos).
|
||||
"""
|
||||
try:
|
||||
print("Monitoreando el uso de memoria RAM. Presiona Ctrl+C para detener.")
|
||||
while True:
|
||||
# Obtener el porcentaje de memoria usada
|
||||
memory_usage = psutil.virtual_memory().percent
|
||||
print(f"Uso de Memoria RAM: {memory_usage:.2f}%")
|
||||
time.sleep(interval)
|
||||
except KeyboardInterrupt:
|
||||
print("\nMonitoreo detenido.")
|
||||
def scan_network(ip_range):
|
||||
# Crear un escáner Nmap
|
||||
nm = nmap.PortScanner()
|
||||
print(f"Escaneando la red {ip_range}...")
|
||||
nm.scan(hosts=ip_range, arguments='-sn')
|
||||
devices = []
|
||||
for host in nm.all_hosts():
|
||||
if nm[host].state() == "up":
|
||||
mac = nm[host]['addresses'].get('mac', 'No MAC address found')
|
||||
devices.append({'ip': nm[host]['addresses']['ipv4'], 'mac': mac})
|
||||
return devices
|
||||
|
||||
# Llama al método para monitorear la memoria
|
||||
print_memory_usage()
|
||||
|
||||
network_range = get_network_range()
|
||||
devices = scan_network(network_range)
|
||||
# Mostrar resultados
|
||||
for device in devices:
|
||||
print(f"IP: {device['ip']}, MAC: {device['mac']}")
|
Loading…
Reference in New Issue