pyshark 实时捕获与显示过滤器
我发现了一个不错的Python模块叫做pyshark,听说它可以像tshark一样使用,并且支持bpf过滤。我实际上是在寻找一种实时捕获的选项,能够使用bpf过滤和显示过滤,这样我就可以对这些数据进行其他处理,并将它们存储到数据库中,以便后续分析。
根据文档,pyshark可以进行实时捕获,但我不知道如何将每个接收到的数据包显示出来并发送到文件或数据库。我正在运行一个IPv6实验室网络。
这是一个示例Python脚本:
import pyshark
capture = pyshark.LiveCapture(interface='eth1',bpf_filter="tcp and port 80")
capture.sniff(timeout=20)
在超时后,我可以打印时间和纪元时间,但只能针对每个数据包。其他部分的数据我无法看到。
print capture[1].sniff_time
print capture[1].sniff_timestamp
我会很感激任何帮助和指导,想知道如何实现实时捕获,并获取每个数据包的数据以发送到数据库。
2 个回答
1
你不能直接获取原始的数据包内容,但你可以通过访问相关的层来获取数据包的各个字段,比如可以用 packet.udp.src_port 来获取UDP协议中的源端口。你可以通过打印数据包来轻松查看所有字段。
2
希望这能帮到你,这段代码是用来捕获数据包的,设置了1秒的超时时间,然后把它们取出来。
import pyshark
capture = pyshark.LiveCapture(interface=r'\Device\NPF_{D41D8EE1-2739-4FA1-8873-024D3F68E9E1}',
output_file=r'C:\Temp\samp1.pcap')
capture.sniff(timeout=1)
pkts = [pkt for pkt in capture._packets]
print(len(capture))
capture.close()
不过在使用capture.close()的时候,似乎会出现一些asyncio的异常。不过这对我们的代码没有影响。
输出结果如下:
94
taking long time to close proactor
Task exception was never retrieved
future: <Task finished coro=<_close_async() done, defined at C:\Python34\lib\site-packages\pyshark\capture\capture.py:409> exception=RuntimeError('Set changed size during iteration',)>
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\trollius\tasks.py", line 255, in _step
result = next(coro)
File "C:\Python34\lib\site-packages\pyshark\capture\capture.py", line 411, in _close_async
for process in self.running_processes:
RuntimeError: Set changed size during iteration
Task was destroyed but it is pending!
task: <Task pending coro=<packets_from_tshark() running at C:\Python34\lib\site-packages\pyshark\capture\capture.py:261> wait_for=<Task finished coro=<_close_async() done, defined at C:\Python34\lib\site-packages\pyshark\capture\capture.py:409> exception=RuntimeError('Set changed size during iteration',)>>
Process finished with exit code 0