Thursday, 7 December 2023

python- tcpdump code

from scapy.all import sniff, TCP, IP, raw

import datetime

import logging

 

# Configuration

SERVER_A_IP = "192.168.1.10"  # Replace with Server A's IP

SERVER_A_PORT = 9092          # Port on Server A used to send data

SERVER_B_IP = "192.168.1.20"  # Replace with Server B's IP

 

# Logging setup

logging.basicConfig(

    filename="server_b_pull.log",  # Log file

    level=logging.INFO,

    format="%(asctime)s - %(message)s",

    datefmt="%Y-%m-%d %H:%M:%S"

)

 

def log_and_print(message):

    """Logs the message to a file and prints it to the console."""

    print(message)

    logging.info(message)

 

def packet_callback(packet):

    """Callback function to process captured packets."""

    arrival_time = datetime.datetime.now()

 

    # Ensure the packet has IP and TCP layers

    if IP in packet and TCP in packet:

        ip_src = packet[IP].src

        ip_dst = packet[IP].dst

        tcp_sport = packet[TCP].sport

        tcp_dport = packet[TCP].dport

 

        # Filter packets coming from Server A on port 9092 to Server B

        if ip_src == SERVER_A_IP and tcp_sport == SERVER_A_PORT and ip_dst == SERVER_B_IP:

            # Extract raw data

            raw_data = raw(packet)

 

            # Log general packet information

            log_and_print(f"Packet from {ip_src}:{tcp_sport} -> {ip_dst}:{tcp_dport}")

            log_and_print(f"  Raw Packet Data: {raw_data.hex()}")

 

            # Attempt to decode payload and extract timestamp (if applicable)

            try:

                payload = raw_data.decode("utf-8")  # Assuming payload is UTF-8 encoded

                source_time_ns = int(payload.split(",")[0])  # Adjust based on payload format

                source_time = datetime.datetime.fromtimestamp(source_time_ns / 1e9)

 

                # Calculate latency

                latency = (arrival_time - source_time).total_seconds() * 1000  # Convert to milliseconds

                log_and_print(f"  Source Timestamp: {source_time}, Arrival Time: {arrival_time}, Latency: {latency:.2f} ms")

            except Exception as e:

                log_and_print(f"  Error decoding payload or calculating latency: {e}")

 

            log_and_print("-" * 50)

 

# Define the packet filter

packet_filter = f"tcp and src host {SERVER_A_IP} and src port {SERVER_A_PORT} and dst host {SERVER_B_IP}"

 

# Start sniffing packets

log_and_print(f"Starting packet capture for traffic from {SERVER_A_IP}:{SERVER_A_PORT} to Server B ({SERVER_B_IP})...")

sniff(filter=packet_filter, prn=packet_callback, store=False, iface="any")




https://pypi.org/project/psutil/#files
https://pypi.org/project/scapy/#files

No comments:

Post a Comment