pythonpython-3.xwiresharkpyshark

pyshark - How can I print destination ip during livecapture?


I am new to pyshark. I am trying to print in the terminal the "destination ip" from the handshakes packets during livecapture with udp filter. (python3)

I couldn't find something useful in hours so this is my last option. Here is my attempt.

import pyshark

file = "C:/Users/S0B0/Desktop/capture/output6" +  ".cap"
output = open(file, "w")
time = 86399

capture = pyshark.LiveCapture(interface="Ethernet",bpf_filter="udp",output_file=file,only_summaries=True)
capture.set_debug()
capture.sniff(timeout=time)

for p in capture:
    if hasattr(p, 'udp'):
        print(p.udp.srcport + ' -- ' + p.udp.dstport)

output.close()

Solution

  • Is this what you are trying to do?

    capture = pyshark.LiveCapture(interface="en0")
    capture.set_debug()
    for packet in capture.sniff_continuously():
    if hasattr(packet, 'udp'):
        protocol = packet.transport_layer
        source_address = packet.ip.src
        source_port = packet[packet.transport_layer].srcport
        destination_address = packet.ip.dst
        destination_port = packet[packet.transport_layer].dstport
        print(f'{protocol}  {source_address}:{source_port} --> {destination_address}:{destination_port}')
    

    I have a document and code examples on GitHub named pyshark packet analysis that you might find useful.