Loading Packet Captures in Scapy

Learn how to load packet capture files into Python’s Scapy library for further analysis.

Introduction to packet captures

Scapy is a Python library that simplifies network traffic analysis and the creation of network clients and servers. It integrates a depth of knowledge about how network protocols and packets work, making it possible to define complex functionality within a few lines of code.

Scapy can monitor live network traffic or read network traffic data from a packet capture (PCAP) generated using tcpdump, Wireshark, or similar tools. The following figure shows a sample workflow using Scapy.

Press + to interact
Sample workflows using Scapy for network traffic analysis
Sample workflows using Scapy for network traffic analysis

Packet captures allow network traffic to be stored for later analysis. This packet capture contains some HTTP and DNS traffic. Since neither of these protocols is encrypted, the full contents of the packets are visible in Wireshark.

Network traffic captures can be analyzed for various purposes. Some examples include the following:

  • Malware analysis: Malware commonly communicates with command and control (C2) servers over the network. Traffic analysis can reveal how the malware works and its actions on a system.

  • Network mapping: Port scanners and vulnerability scanners actively collect information about the systems and software present in a network. This can also be accomplished passively by monitoring network traffic and identifying communicating computers and applications.

  • Credential capture: Some insecure network protocols transmit user credentials in plaintext. Capturing and analyzing network traffic can give attackers access to user accounts with these protocols.

  • Digital forensics: After a cybersecurity incident, forensics investigators attempt to reconstruct what happened. Analyzing network traffic can help reconstruct some of the stages of an attack.

Packet captures in Scapy

Now, let’s try opening this packet capture in Scapy. First, we need to import the Scapy library into Python, which we can accomplish via the from scapy.all import * command. This imports all of Scapy’s functionality, ensuring that we have what we need to work with the network packets.

Once Scapy is loaded, the rdpcap function is available. Calling rdpcap with the name of a packet capture file as an argument loads that packet capture into a variable.

The code block below includes a simple program for loading the PCAP into Scapy. Try it out!

Press + to interact
from scapy.all import *
packets = rdpcap('http.cap')
print(len(packets))

Running this code outputs “43,” which is the number of packets contained in the capture file that we viewed above. This shows that the file was loaded successfully into the packets variable, and we’re ready to start viewing and working with the packets that it contains.