SoFunction
Updated on 2025-03-04

Analyzing wireshark files using Python

1 pyshark library

Supports wireless resolution, etc.

Install pyshark

pip install pyshark

2 dpkt library

This is also a library for analyzing pcap files, and is the fastest of all the parsing pcap libraries.

Official reference documents:

/en/latest/print_packets.html

/en/latest/#examples-in-dpkt-examples

Install

pip install dpkt

3 Application examples

dpkt read pcap file

f = open('','rb')
pcap = (f)
# ts is the timestemp timestamp, and buf (binary data) is the data packet information of the subject.for ts,buf in pcap:
    pass

Get the IP address of each packet

#Convert the binary data from buf into an Ethernet class objecteth = (buf)
 
ip_src =  #Here is the source ip for obtaining this data packet#It should be noted that the source ip here is returned in binary mode. If we want to get the dotted decimal IP address#You can do thisdef inet_to_str(inet):
    try:
        return socket.inet_ntop(socket.AF_INET,inet)
    except:
        return False#Is IPv6 discarded here because it needs to be specific        #If you want IPv6 to be available, this is the case        #return socket.inet_ntop(socket.AF_INET6,inet)
ip_src = inet_to_str()
ip_dst = inet_to_str()#Purpose ip\

Get the IP in the message

#coding=utf-8
import dpkt
import socket
import time
 
def inet_to_str(inet):
    try:
        return socket.inet_ntop(socket.AF_INET,inet)
    except:
        return False
 
def getip():
    f = open('','rb')#If you want to open in rb, if you open in r, you will report an error    pcap = (f)
    for ts,buf in pcap:
        print(ts)Print time stamp
        eth=(buf)
 
        #This is also filtering out packets without IP segments        if  != .ETH_TYPE_IP:
            continue
 
        ip = 
        ip_src = inet_to_str()
        ip_dst = inet_to_str()
        print(ip_src+'-->'+ip_dst)
 
if __name__=='__main__':
getip()

Modify the source ip and purpose in the message

import dpkt
import os
import socket

test = open("","wb")
writer = (test)
f=open("",'rb')
packets = (f)
for ts,buf in packets:
    eth = (buf)

    # Here is the conversion of dotted decimal to binary     = socket.inet_pton(socket.AF_INET, "192.168.1.1")
     = socket.inet_pton(socket.AF_INET, "192.168.1.2")
    (eth,ts=ts)#Not adding the ts parameter, the packet timestamp will default to the current time    ()
()

This is the end of this article about using Python to analyze wireshark files. For more related Python analysis of wireshark files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!