Reputation: 1340
I am trying to find ways to monitor the network traffic of a Python-based package. One suggested approach is by incorporating WireShark to the package. I have never done anything like this before, and could not find any tutorials on the Internet regarding this. And, whatever I could gather, it seems to be suggested using PyShark as wrapper to perform the task. Could someone please offer me some guidance such as code snippets or pointers on how I could tackle the task? Any help would be much appreciated.
Upvotes: 1
Views: 11005
Reputation: 1340
Figured out I can probably use TShark
or pyshark
for my purposes to monitor the network traffic of a Python-based package. For details please see official documentation at https://www.wireshark.org/docs/man-pages/tshark.html. Can follow the sources below for what I originally wanted to do:
Update as of July 17, 2019:
So the main thing to note for me was to note that there are two methods in pyshark I could use to capture packets, namely FileCapture
or LiveCapture
. FileCapture
is mostly for reading from a capture file, so it was not that useful for me, as I wanted to capture some live event. On the other hand, LiveCapture
is for reading from a live interface, so I opted to use it for monitoring live network traffic. So I wrote the following code snippet to capture some tcp packets transmitted on my laptop:
@staticmethod
def get_packet_info(interface=None):
"""
Returns the size of the transmitted data using Wireshark.
Args:
interface: A string. Name of the interface to sniff on.
Returns: Size of the packet sent over WebSockets in a given event.
"""
if interface is None:
raise Exception("Please provide the interface used.")
else:
capture = pyshark.LiveCapture(interface=interface)
capture.sniff(timeout=60)
for packet in capture:
try:
packet_info = packet.pretty_print()
except:
raise Exception("Cannot determine packet info.")
return packet_info
The argument of sniff
can be changed from timeout
to something like packet_count
. Additionally, I could add more attributes to LiveCapture for better control.
Upvotes: 3