Intro to PyShark

for Programmatic Packet Analysis

Nov - 2014 (~3 minutes read time)

I can hardly believe it took me this long to find PyShark, but I am very glad I did! PyShark is a wrapper for the Wireshark CLI interface, tshark, so all of the Wireshark decoders are available to PyShark! It is so amazing that I started a new project just so I could use this amazing new tool: Cloud-Pcap.

You can use PyShark to sniff from a interface or open a saved capture file, as the docs show on the overview page here:

import pyshark

# Open saved trace file 
cap = pyshark.FileCapture('/tmp/mycapture.cap')

# Sniff from interface
capture = pyshark.LiveCapture(interface='eth0')
<LiveCapture (5 packets)>

Using the Capture Object

Nov - 2014 (~2 minutes read time)

Now that we know how to use the FileCapture and LiveCapture modules to capture some packets, let's see what options we have with the returned capture object (truncated list for brevity):

>>> dir(cap)

FileCapture and LiveCapture modules

Nov - 2014 (~4 minutes read time)

The two typical ways to start analyzing packets are via PyShark's FileCapture and LiveCapture modules. The first will import packets from a saved capture file, and the latter will sniff from a network interface on the local machine. Running these modules will return a capture object which I will cover in depth in the next post. For now, let's see what we can do with these two modules.

Using the Packet Object

Nov - 2014 (~5 minutes read time)

So far in this series we've done a lot with capturing packets and working with the capture object, but finally we're going to get to the fun part and finally start playing with some PACKETS!!!!

When we have captured packets in a capture object, they are stored as a list of packet objects. Ā These packet objects will have methods and attributes that give us access to the header and payload info of each packet. Ā As stated in a previous post we have controlĀ for how much info about the packets we store in each packet option through the only_summaries argument in the LiveCapture and ReadCapture modules.