Advertisement
Python253

10sec_packet_capture

Apr 13th, 2024
987
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.78 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: 10sec_packet_capture.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script captures network packets using Scapy and logs packet information to a text file. Additionally, it runs Procmon to capture detailed process information.
  9.  
  10. Requirements:
  11. - Python 3.x
  12. - Scapy library (install using 'pip install scapy')
  13.  
  14. Functions:
  15. 1. packet_logger(packet): Log packet information to the console.
  16. 2. start_capture(): Start capturing network packets using Scapy.
  17. 3. run_procmon(): Run Procmon to capture detailed process information.
  18. 4. stop_procmon(): Stop Procmon capture.
  19.  
  20. Usage:
  21. 1. Ensure Python 3.x is installed on your system.
  22. 2. Install the Scapy library using 'pip install scapy'.
  23. 3. Save the packet_capture.py script to a directory of your choice.
  24. 4. Open a terminal or command prompt.
  25. 5. Navigate to the directory where the packet_capture.py script is saved.
  26. 6. Run the script using the following command:  'python packet_capture.py'
  27. 7. During script execution, network packets will be captured and logged to the console. Procmon will also be started to capture process information.
  28. 8. After capturing packets for the specified duration, the captured packet information will be saved to a text file named 'captured_packets.txt' in the same directory.
  29. 9. The Procmon capture will be automatically stopped after packet capture completes.
  30.  
  31. Additional Notes:
  32. - This script captures network packets using the Scapy library.
  33. - Packet information is logged to the console during packet capture.
  34. - Procmon is started in a separate thread to capture detailed process information simultaneously with packet capture.
  35. - Captured packet information is saved to a text file for further analysis.
  36.  
  37. Demo Output:
  38. # Process Monitor Log (PML) generated for testing purposes
  39. # Packet Captured:
  40. # -----------------
  41. # Protocol: Ether / IPv6 / ICMPv6ND_NS / ICMPv6 Neighbor Discovery Option - Source Link-Layer Address XX:XX:XX:XX:XX:XX
  42. # Packet Payload:
  43. # IPv6 / ICMPv6ND_NS / ICMPv6 Neighbor Discovery Option - Source Link-Layer Address XX:XX:XX:XX:XX:XX
  44.  
  45. # Raw Bytes:
  46. 60 00 00 00 00 20 3a ff fe 80 00 00 00 00 00 00 4a bd ce ff fe 1b dd 59 26 01 06 03 07 01 00 d0 5d c3 b3 ab 6a da 1e 04 87 00 f3 77 00 00 00 00 26 01 06 03 07 01 00 d0 5d c3 b3 ab 6a da 1e 04 01 01 48 bd ce 1b dd 59
  47. """
  48.  
  49. import scapy.all as scapy
  50. from scapy.layers.inet import IP, TCP, UDP
  51. import time
  52. import subprocess
  53. import threading
  54. import os
  55.  
  56. PROC_MON_PATH = r"C:\Program Files\Sysinternals\Procmon.exe"
  57. CAPTURE_DURATION = 10  # Duration of packet capture in seconds
  58.  
  59. def packet_logger(packet):
  60.     """
  61.    Log packet information to the console.
  62.    """
  63.     print("Packet captured:")
  64.     print("-----------------")
  65.     print("Protocol:", packet.summary())
  66.     if IP in packet:
  67.         print("Source IP:", packet[IP].src)
  68.         print("Destination IP:", packet[IP].dst)
  69.     if TCP in packet:
  70.         print("Source Port:", packet[TCP].sport)
  71.         print("Destination Port:", packet[TCP].dport)
  72.         print("TCP Flags:", packet[TCP].flags)
  73.     elif UDP in packet:
  74.         print("Source Port:", packet[UDP].sport)
  75.         print("Destination Port:", packet[UDP].dport)
  76.     print("Packet Payload:")
  77.     if isinstance(packet.payload, bytes):
  78.         print(packet.payload.decode('utf-8', errors='ignore'))
  79.     else:
  80.         print(packet.payload)
  81.     print("\nRaw Bytes:")
  82.     print(bytes(packet.payload))
  83.  
  84. def start_capture():
  85.     """
  86.    Start capturing packets.
  87.    """
  88.     start_time = time.time()
  89.     captured_packets = []
  90.     while time.time() - start_time < CAPTURE_DURATION:
  91.         packet = scapy.sniff(timeout=1)
  92.         if packet:
  93.             captured_packets.extend(packet)  # Extend the list with the packet
  94.             for pkt in packet:
  95.                 packet_logger(pkt)
  96.    
  97.     # Save captured packets to a text file
  98.     with open("captured_packets.txt", "w") as file:
  99.         for packet in captured_packets:
  100.             file.write("Packet captured:\n")
  101.             file.write("-----------------\n")
  102.             file.write("Protocol: {}\n".format(packet.summary()))
  103.             if IP in packet:
  104.                 file.write("Source IP: {}\n".format(packet[IP].src))
  105.                 file.write("Destination IP: {}\n".format(packet[IP].dst))
  106.             if TCP in packet:
  107.                 file.write("Source Port: {}\n".format(packet[TCP].sport))
  108.                 file.write("Destination Port: {}\n".format(packet[TCP].dport))
  109.                 file.write("TCP Flags: {}\n".format(packet[TCP].flags))
  110.             elif UDP in packet:
  111.                 file.write("Source Port: {}\n".format(packet[UDP].sport))
  112.                 file.write("Destination Port: {}\n".format(packet[UDP].dport))
  113.             file.write("Packet Payload:\n")
  114.             if isinstance(packet.payload, bytes):
  115.                 file.write(packet.payload.decode('utf-8', errors='ignore') + "\n")
  116.             else:
  117.                 file.write(str(packet.payload) + "\n")
  118.             file.write("\nRaw Bytes:\n")
  119.             file.write(str(bytes(packet.payload)) + "\n\n")
  120.  
  121. def run_procmon():
  122.     """
  123.    Run Procmon to capture detailed process information.
  124.    """
  125.     try:
  126.         subprocess.Popen([PROC_MON_PATH, "/Quiet", "/Minimized", "/Backingfile", "output.pml"])
  127.         print("Procmon started successfully.")
  128.     except Exception as e:
  129.         print("Error starting Procmon:", e)
  130.  
  131. def stop_procmon():
  132.     """
  133.    Stop Procmon capture.
  134.    """
  135.     try:
  136.         subprocess.run([PROC_MON_PATH, "/Terminate"])
  137.         print("Procmon stopped successfully.")
  138.     except Exception as e:
  139.         print("Error stopping Procmon:", e)
  140.  
  141. if __name__ == "__main__":
  142.     procmon_thread = threading.Thread(target=run_procmon)
  143.     procmon_thread.start()
  144.     start_capture()
  145.     stop_procmon()
  146.  
  147.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement