Analyzing networking traffic using the pyshark library

We can use the pyshark library to analyze the network traffic in Python, since everything Wireshark decodes in each packet is made available as a variable. We can find the source code of the tool in GitHub's repository: https://github.com/KimiNewt/pyshark.

In the PyPI repository, we can find the last version of the library, that is, https://pypi.org/project/pyshark, and we can install it with the pip install pyshark command.

In the documentation of the module, we can see that the main package for opening and analyzing a pcap file is capture.file_capture:

Here's an example that was taken from pyshark's GitHub page. This shows us how, from the Python 3 command-line interpreter, we can read packets stored in a pcap file. This will give us access to attributes such as packet number and complete information for each layer, such as its protocol, IP address, mac address, and flags, where you can see if the packet is a fragment of another:

>> import pyshark
>>> cap = pyshark.FileCapture(‘http.cap')
>>> cap
>>> print(cap[0])

In the following screenshot, we can see the execution of the previous commands, and also see where we passed the pcap file path in the FileCapture method as a parameter

We can apply a filter for DNS traffic only with the display_filter argument in the FileCapture method:

import pyshark
cap = pyshark.FileCapture('http.cap', display_filter="dns")
for pkt in cap:
print(pkt.highest_layer)

In the following screenshot, we can see the execution of the previous commands:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset