如何使用python通过特定协议过滤pcap文件? [英] How can I filter a pcap file by specific protocol using python?

查看:106
本文介绍了如何使用python通过特定协议过滤pcap文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 pcap 文件,我想按协议过滤,即如果我想按 HTTP 协议过滤,除了 HTTP 数据包之外的任何内容都将保留在 pcap 文件中.

I have some pcap files and I want to filter by protocol, i.e., if I want to filter by HTTP protocol, anything but HTTP packets will remain in the pcap file.

有一个名为 openDPI 的工具,它非常适合我的需要,但没有包装python语言.

There is a tool called openDPI, and it's perfect for what I need, but there is no wrapper for python language.

有谁知道可以做我需要的任何 python 模块吗?

Does anyone knows any python modules that can do what I need?

谢谢

编辑 1:

HTTP 过滤只是一个例子,我想过滤很多协议.

HTTP filtering was just an example, there is a lot of protocols that I want to filter.

编辑 2:

我尝试过 Scapy,但我不知道如何正确过滤.过滤器只接受 Berkeley Packet Filter 表达式,即我不能从上层应用 msn、HTTP 或其他特定过滤器.有人可以帮我吗?

I tried Scapy, but I don't figure how to filter correctly. The filter only accepts Berkeley Packet Filter expression, i.e., I can't apply a msn, or HTTP, or another specific filter from upper layer. Can anyone help me?

推荐答案

一个使用 Scapy 的快速示例,因为我刚刚写了一个:

A quick example using Scapy, since I just wrote one:

pkts = rdpcap('packets.pcap')
ports = [80, 25]
filtered = (pkt for pkt in pkts if
    TCP in pkt and
    (pkt[TCP].sport in ports or pkt[TCP].dport in ports))
wrpcap('filtered.pcap', filtered)

这将过滤掉既不是 HTTP 也不是 SMTP 的数据包.如果你想要所有的数据包 HTTP 和 SMTP,第三行应该是:

That will filter out packets that are neither HTTP nor SMTP. If you want all the packets but HTTP and SMTP, the third line should be:

filtered = (pkt for pkt in pkts if
    not (TCP in pkt and
    (pkt[TCP].sport in ports or pkt[TCP].dport in ports)))
wrpcap('filtered.pcap', filtered)

这篇关于如何使用python通过特定协议过滤pcap文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆