使用Python分析wireshark文件
1 pyshark庫
支持wireshark的解析等。
安裝pyshark
pip install pyshark
2 dpkt庫
這也是一個用于分析pcap文件的庫,是所有分析pcap庫中最快的一個。
官方參考文檔:
https://dpkt.readthedocs.io/en/latest/print_packets.html
https://dpkt.readthedocs.io/en/latest/examples.html#examples-in-dpkt-examples
安裝
pip install dpkt
3 應(yīng)用實例
dpkt讀pcap文件
f = open('new1.pcap','rb')
pcap = dpkt.pcap.Reader(f)
# ts是timestemp時間戳,buf(二進制數(shù)據(jù))是主體的數(shù)據(jù)包信息。
for ts,buf in pcap:
pass
獲取每個數(shù)據(jù)包的ip地址
#由buf這個二進制數(shù)據(jù)轉(zhuǎn)化為Ethernet類的對象
eth = dpkt.ethernet.Ethernet(buf)
ip_src = eth.data.src #這里是獲取這個數(shù)據(jù)包的源ip
#要注意的是,這里的源ip是以二進制的方式返回的,如果我們要獲取點分十進制的ip地址
#可以這樣做
def inet_to_str(inet):
try:
return socket.inet_ntop(socket.AF_INET,inet)
except:
return False#這里因為具體需要把IPv6給丟棄了
#如果希望IPv6也能獲取可以這樣
#return socket.inet_ntop(socket.AF_INET6,inet)
ip_src = inet_to_str(eth.data.src)
ip_dst = inet_to_str(eth.data.dst)#目的ip\
獲取報文中的ip
#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('new1.pcap','rb')#要以rb方式打開,用r方式打開會報錯
pcap = dpkt.pcap.Reader(f)
for ts,buf in pcap:
print(ts)打印時間戳
eth=dpkt.ethernet.Ethernet(buf)
#這里也是對沒有IP段的包過濾掉
if eth.type != dpkt.ethernet.ETH_TYPE_IP:
continue
ip = eth.data
ip_src = inet_to_str(ip.src)
ip_dst = inet_to_str(ip.dst)
print(ip_src+'-->'+ip_dst)
if __name__=='__main__':
getip()
修改報文中的源ip和目的
import dpkt
import os
import socket
test = open("new.pcap","wb")
writer = dpkt.pcap.Writer(test)
f=open("old.pcap",'rb')
packets = dpkt.pcap.Reader(f)
for ts,buf in packets:
eth = dpkt.ethernet.Ethernet(buf)
# 這里是將點分十進制轉(zhuǎn)化成二進制
eth.data.src = socket.inet_pton(socket.AF_INET, "192.168.1.1")
eth.data.dst = socket.inet_pton(socket.AF_INET, "192.168.1.2")
writer.writepkt(eth,ts=ts)#不加ts參數(shù),數(shù)據(jù)包時間戳會默認為當前時間
test.flush()
test.close()
到此這篇關(guān)于使用Python分析wireshark文件的文章就介紹到這了,更多相關(guān)Python分析wireshark文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Django使用redis緩存服務(wù)器的實現(xiàn)代碼示例
這篇文章主要介紹了Django使用redis緩存服務(wù)器的實現(xiàn)代碼示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
一個基于flask的web應(yīng)用誕生 使用模板引擎和表單插件(2)
一個基于flask的web應(yīng)用誕生第二篇,這篇文章主要介紹了如何使用jinja2模板引擎和wtf表單插件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
Flask搭建虛擬環(huán)境并運行第一個flask程序
這篇文章主要介紹了Flask搭建虛擬環(huán)境并運行第一個flask程序,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04
Python深度學習pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet
這篇文章主要為大家講解了Python深度學習中的pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet的示例解析,有需要的朋友可以借鑒參考下希望能夠有所幫助2021-10-10

