首页 > 解决方案 > 使用 python 和 pyshark 跟踪 TCP 流

问题描述

在 Wireshark 中手动执行此操作时,我右键单击一个数据包 -> 跟随 -> TCP 流,将打开一个包含相关信息的新窗口。有没有办法通过使用 pyshark 模块和 python 2.7 来做同样的事情并获取这些信息?注意:我通过发送无效的 HTTP 方法进行请求测试,因此在这里寻找 HTTP 层不起作用。

标签: python-2.7wiresharkpyshark

解决方案


是的,您可以使用 python 和 pyshark 跟踪 TCP 流。下面是一个基本的概念证明。

"""
Follow a TCP stream with pyshark.

"""
import pyshark

# Change FILENAME to your pcap file's name.
FILENAME = "myfile.pcap"
# Change STREAM_NUMBER to the stream number you want to follow.
STREAM_NUMBER = 0

# open the pcap file, filtered for a single TCP stream 
cap = pyshark.FileCapture(
    FILENAME,
    display_filter='tcp.stream eq %d' % STREAM_NUMBER)

while True:
    try:
        p = cap.next()
    except StopIteration:  # Reached end of capture file.
        break
    try:
        # print data from the selected stream
        print(p.data.data.binary_value)
    except AttributeError:  # Skip the ACKs.
        pass

我验证了上面的代码适用于 python 2.7.13 和 python 3.6.6。

注意:由于较新版本的pyshark只支持 python 3.5+,如果你必须使用 python 2.7,你会被pyshark-legacy pip 包卡住。


推荐阅读