Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: 10sec_packet_capture.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script captures network packets using Scapy and logs packet information to a text file. Additionally, it runs Procmon to capture detailed process information.
- Requirements:
- - Python 3.x
- - Scapy library (install using 'pip install scapy')
- Functions:
- 1. packet_logger(packet): Log packet information to the console.
- 2. start_capture(): Start capturing network packets using Scapy.
- 3. run_procmon(): Run Procmon to capture detailed process information.
- 4. stop_procmon(): Stop Procmon capture.
- Usage:
- 1. Ensure Python 3.x is installed on your system.
- 2. Install the Scapy library using 'pip install scapy'.
- 3. Save the packet_capture.py script to a directory of your choice.
- 4. Open a terminal or command prompt.
- 5. Navigate to the directory where the packet_capture.py script is saved.
- 6. Run the script using the following command: 'python packet_capture.py'
- 7. During script execution, network packets will be captured and logged to the console. Procmon will also be started to capture process information.
- 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.
- 9. The Procmon capture will be automatically stopped after packet capture completes.
- Additional Notes:
- - This script captures network packets using the Scapy library.
- - Packet information is logged to the console during packet capture.
- - Procmon is started in a separate thread to capture detailed process information simultaneously with packet capture.
- - Captured packet information is saved to a text file for further analysis.
- Demo Output:
- # Process Monitor Log (PML) generated for testing purposes
- # Packet Captured:
- # -----------------
- # Protocol: Ether / IPv6 / ICMPv6ND_NS / ICMPv6 Neighbor Discovery Option - Source Link-Layer Address XX:XX:XX:XX:XX:XX
- # Packet Payload:
- # IPv6 / ICMPv6ND_NS / ICMPv6 Neighbor Discovery Option - Source Link-Layer Address XX:XX:XX:XX:XX:XX
- # Raw Bytes:
- 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
- """
- import scapy.all as scapy
- from scapy.layers.inet import IP, TCP, UDP
- import time
- import subprocess
- import threading
- import os
- PROC_MON_PATH = r"C:\Program Files\Sysinternals\Procmon.exe"
- CAPTURE_DURATION = 10 # Duration of packet capture in seconds
- def packet_logger(packet):
- """
- Log packet information to the console.
- """
- print("Packet captured:")
- print("-----------------")
- print("Protocol:", packet.summary())
- if IP in packet:
- print("Source IP:", packet[IP].src)
- print("Destination IP:", packet[IP].dst)
- if TCP in packet:
- print("Source Port:", packet[TCP].sport)
- print("Destination Port:", packet[TCP].dport)
- print("TCP Flags:", packet[TCP].flags)
- elif UDP in packet:
- print("Source Port:", packet[UDP].sport)
- print("Destination Port:", packet[UDP].dport)
- print("Packet Payload:")
- if isinstance(packet.payload, bytes):
- print(packet.payload.decode('utf-8', errors='ignore'))
- else:
- print(packet.payload)
- print("\nRaw Bytes:")
- print(bytes(packet.payload))
- def start_capture():
- """
- Start capturing packets.
- """
- start_time = time.time()
- captured_packets = []
- while time.time() - start_time < CAPTURE_DURATION:
- packet = scapy.sniff(timeout=1)
- if packet:
- captured_packets.extend(packet) # Extend the list with the packet
- for pkt in packet:
- packet_logger(pkt)
- # Save captured packets to a text file
- with open("captured_packets.txt", "w") as file:
- for packet in captured_packets:
- file.write("Packet captured:\n")
- file.write("-----------------\n")
- file.write("Protocol: {}\n".format(packet.summary()))
- if IP in packet:
- file.write("Source IP: {}\n".format(packet[IP].src))
- file.write("Destination IP: {}\n".format(packet[IP].dst))
- if TCP in packet:
- file.write("Source Port: {}\n".format(packet[TCP].sport))
- file.write("Destination Port: {}\n".format(packet[TCP].dport))
- file.write("TCP Flags: {}\n".format(packet[TCP].flags))
- elif UDP in packet:
- file.write("Source Port: {}\n".format(packet[UDP].sport))
- file.write("Destination Port: {}\n".format(packet[UDP].dport))
- file.write("Packet Payload:\n")
- if isinstance(packet.payload, bytes):
- file.write(packet.payload.decode('utf-8', errors='ignore') + "\n")
- else:
- file.write(str(packet.payload) + "\n")
- file.write("\nRaw Bytes:\n")
- file.write(str(bytes(packet.payload)) + "\n\n")
- def run_procmon():
- """
- Run Procmon to capture detailed process information.
- """
- try:
- subprocess.Popen([PROC_MON_PATH, "/Quiet", "/Minimized", "/Backingfile", "output.pml"])
- print("Procmon started successfully.")
- except Exception as e:
- print("Error starting Procmon:", e)
- def stop_procmon():
- """
- Stop Procmon capture.
- """
- try:
- subprocess.run([PROC_MON_PATH, "/Terminate"])
- print("Procmon stopped successfully.")
- except Exception as e:
- print("Error stopping Procmon:", e)
- if __name__ == "__main__":
- procmon_thread = threading.Thread(target=run_procmon)
- procmon_thread.start()
- start_capture()
- stop_procmon()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement