利用Python库Scapy解析pcap文件

每次写博客都是源于纳闷,python解析pcap这么常用的例子网上竟然没有,全是一堆命令行执行的python,能用吗?玩呢?

pip安装scapy,然后解析pcap:

import scapy
from scapy.all import *
from scapy.utils import PcapReader
packets=rdpcap("./test.pcap")
for data in packets:
    if 'UDP' in data:
        s = repr(data)
        print(s)
        print(data['UDP'].sport)
        break

打印s,是为了看到所有的字段:

<Ether  dst=ff:ff:ff:ff:ff:ff src=30:fc:68:33:7a:e2 type=0x800 |<IP  version=4 ihl=5 tos=0x0 len=143 id=37312 flags= frag=0 ttl=64 proto=udp chksum=0x644d src=192.168.1.1 dst=192.168.1.255 options=[] |<UDP  sport=1024 dport=5001 len=123 chksum=0x3051 |<Raw  load='\x01\x01\x0e\x00\xe1+\x83\xc7\xb2\x9f\x00e\x00\x00\x00\x06\x00\tTL-WR886N\x00\x0b\x00\x035.0\x00\x07\x00\x01\x01\x00\x05\x00\x1130-fc-68-33-7a-e2\x00\x08\x00\x0b192.168.1.1\x00\t\x00\ntplogin.cn\x00\n\x00\rTL-WR886N 5.0\x00\x0c\x00\x051.7.3' |>>>>

然后就能用data['UDP'].sport打印udp的源端口了。

现在基本的字段都能看到了,如果还想看别的协议的字段,可以参考源码:

https://github.com/secdev/scapy/tree/master/scapy/layers

L2层在l2.python,ip,tcp等在inet.py中,例如tcp的一些字段名称在这:


已标记关键词 清除标记
写了个python程序解析流量数据包,用的是scapy。读取流量较少的pcap文件时可以顺利运行,读取大点的pcap包就会报错。 错误信息如下: ``` Traceback (most recent call last): File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\scapy\packet.py", line 235, in __getattr__ fld, v = self.getfield_and_val(attr) TypeError: 'NoneType' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\scapy\packet.py", line 235, in __getattr__ fld, v = self.getfield_and_val(attr) TypeError: 'NoneType' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Paper\sta\pcap\特征提取.py", line 22, in <module> bufLen.append(data.len) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\scapy\packet.py", line 237, in __getattr__ return self.payload.__getattr__(attr) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\scapy\packet.py", line 237, in __getattr__ return self.payload.__getattr__(attr) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\scapy\packet.py", line 235, in __getattr__ fld, v = self.getfield_and_val(attr) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\scapy\packet.py", line 1291, in getfield_and_val raise AttributeError(attr) AttributeError: len ``` 源代码部分: ``` from scapy.all import * from scapy.utils import PcapReader rd = PcapReader('./a.pcap') while True: data = rd.read_packet() if data is None: break else: ''' 分析处理过程 ''' rd.close() ``` 源代码处理过程应该没问题,毕竟可以运行处理小数据包,但数据量一大就会报错。 而且有时候不稳定,简单的同样的代码有时可以运行成功,有时也会报上面的错,我想是不是系统的问题,我用的是在windows10,内存16G应该足够大,为什么会报错呢,求大神解答!
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页