Search code examples
python-2.7wiresharkpyshark

Follow TCP stream using python and pyshark


When doing it manually in Wireshark, I right click a packet -> follow -> TCP stream a new window would be opened with the relevant information. Is there a way to do the exact same thing and get this information by using pyshark module and python 2.7? NOTE: I'm making request testing by sending a non valid HTTP methods , so looking for HTTP layer won't work here.


Solution

  • Yes, you can follow a TCP stream with python and pyshark. Below is a basic proof of concept.

    """
    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
    

    I verified the above code works for python 2.7.13 and python 3.6.6.

    Note: Since newer versions of pyshark only support python 3.5+, if you must use python 2.7, you're stuck with the pyshark-legacy pip package.