简体   繁体   中英

Print packet protocol type using PyShark

I want to print all the protocols of the packet (ie: ICMP, ARP, TCP, UDP, etc.) but I am getting only TCP and UDP. I am using pyshark and python to capture packets.

import pyshark 

capture = pyshark.LiveCapture(interface='eth0')
capture.sniff(timeout=50)
for packet in capture.sniff_continuously():
    localtime = time.asctime(time.localtime(time.time()))
    protocol = packet.transport_layer
    src_addr = packet.ip.src
    src_port = packet[packet.transport_layer].srcport
    dst_addr = packet.ip.dst
    dst_port = packet[packet.transport_layer].dstport

    print (localtime,"\t",protocol,"\t", src_addr,"\t", src_port,"\t", dst_addr, "\t", dst_port)

The reason that you are only getting TCP and UDP packets is because you are calling the transport_layer .

Reference: Pyshark Dynamic Layer References

Here is one way to see the layers of an individual packet:

import pyshark

capture = pyshark.LiveCapture('en0')
for packet in capture:
    protocol = packet.layers
    print(protocol)
    filtered...
    [<ETH Layer>, <IP Layer>, <TCP Layer>, <NBSS Layer>, <SMB2 Layer>]
    [<ETH Layer>, <IP Layer>, <TCP Layer>]
    [<ETH Layer>, <IP Layer>, <UDP Layer>, <QUIC Layer>]
    [<ETH Layer>, <IP Layer>, <TCP Layer>, <HTTP Layer>]
    [<ETH Layer>, <IP Layer>, <TCP Layer>, <TLS Layer>]
    [<ETH Layer>, <ARP Layer>]
    truncated...

You can access the highest packet layer this way:

import pyshark

capture = pyshark.LiveCapture('en0')
for packet in capture:
    layer = packet.highest_layer
    print(layer)
    filtered...
    ARP
    DNS
    TCP
    HTTP
    UDP
    truncated...

I'm not sure what your use case is for parsing all the data related to a packet.

Here is a document that I wrote on parsing packet data with pyshark .

Here is some documentation for pyshark that provides information on parsing packet data.

If you need any additional help, please let me know and I will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM