使用 python 和 pyshark 跟踪 TCP 流

Eli*_*osh 2 wireshark python-2.7 pyshark

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

ama*_*ath 5

是的,您可以使用 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
Run Code Online (Sandbox Code Playgroud)

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

注意:由于较新版本的pyshark仅支持 python 3.5+,因此如果必须使用 python 2.7,则只能使用pyshark-legacy pip 包。