from scapy.all import sniff from scapy.layers.inet import IP, TCP, UDP, ICMP from scapy.packet import Raw import os import datetime def save_packet_to_file(packet): """Guarda el paquete en un archivo de registro para análisis posterior.""" with open("packet_log.txt", "a") as log_file: log_file.write(f"{datetime.datetime.now()} - {packet.summary()}\n") log_file.write(f"{packet.show(dump=True)}\n\n") def packet_callback(packet): """Procesa y retorna información del paquete capturado.""" packet_info = [] if IP in packet: ip_layer = packet[IP] packet_info.append(f"[+] Capturado un paquete:") packet_info.append(f" Origen: {ip_layer.src}") packet_info.append(f" Destino: {ip_layer.dst}") packet_info.append(f" Protocolo: {ip_layer.proto}") if TCP in packet: tcp_layer = packet[TCP] packet_info.append(f" Puerto origen: {tcp_layer.sport}") packet_info.append(f" Puerto destino: {tcp_layer.dport}") elif UDP in packet: udp_layer = packet[UDP] packet_info.append(f" Puerto origen: {udp_layer.sport}") packet_info.append(f" Puerto destino: {udp_layer.dport}") elif ICMP in packet: packet_info.append(" Tipo de ICMP detectado.") if Raw in packet: payload = packet[Raw].load.decode(errors="ignore") packet_info.append(f" Datos (Raw): {payload}") if "youtube.com" in payload or "YouTube" in payload: packet_info.append(f"\n[!!!] Posible enlace de YouTube detectado:") packet_info.append(payload) packet_info.append(f"[Paquete completo]: {packet.summary()}") # Guardar el paquete en un archivo save_packet_to_file(packet) return "\n".join(packet_info)