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') capture.sniff(timeout=10) <LiveCapture (5 packets)>
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) Out: ['apply_on_packets', 'close', 'current_packet', 'display_filter', 'encryption', 'input_filename', 'next', 'next_packet']
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.
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.