【问题标题】:How to get the protocol name in PyShark?如何在 PyShark 中获取协议名称?
【发布时间】:2023-02-01 03:19:22
【问题描述】:

使用 PyShark,如何从数据包原型字段上的数字中获取带有 IP 协议名称的字符串?

例如,将 6 转换为“TCP”。

【问题讨论】:

    标签: python tcp protocols scapy pyshark


    【解决方案1】:

    您可以从 socket module of the Python Standard Library 获取协议编号 as defined by IANA 的映射:

    import socket
    ip_proto={v:k[8:] for (k,v) in vars(socket).items() if k.startswith('IPPROTO')}
    

    此字典理解使用 vars 内置函数从 socket module__dict__ 属性中提取 IP 协议。

    然后将其用作:

    >>> ip_proto.get(1)
    'ICMP'
    >>> ip_proto.get(2)
    'IGMP'
    >>> ip_proto.get(6)
    'TCP'
    

    【讨论】:

      【解决方案2】:

      这是使用PyShark 完成用例的一种方法。

      import pyshark
      import re as regex
      
      capture = pyshark.LiveCapture(interface='en0')
      for packet in capture:
          if 'IPV6 Layer' in str(packet.layers):
              protocol = regex.search(r'(Next Header:)(.*)', str(packet.ipv6))
              protocol_type = protocol.group(2).strip().split(' ')[0]
              protocol_number = protocol.group(2).strip().split(' ')[1]
              print(f'(Internet Protocol: IPv6, '
                    f'Protocol Type: {protocol_type}, '
                    f'Protocol Number: {protocol_number}')
          elif 'IP Layer' in str(packet.layers):
              protocol = regex.search(r'(Protocol:)(.*)', str(packet.ip))
              protocol_type = protocol.group(2).strip().split(' ')[0]
              protocol_number = protocol.group(2).strip().split(' ')[1]
              print(f'(Internet Protocol: IPv4, '
                    f'Protocol Type: {protocol_type}, '
                    f'Protocol Number: {protocol_number}')
      

      输出:

      (Internet Protocol: IPv4, Protocol Type: TCP, Protocol Number: (6)
      (Internet Protocol: IPv4, Protocol Type: UDP, Protocol Number: (17)
      (Internet Protocol: IPv6, Protocol Type: ICMPv6, Protocol Number: (58)
      truncated...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 2011-06-01
        • 1970-01-01
        • 2012-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多