【发布时间】:2023-02-01 03:19:22
【问题描述】:
使用 PyShark,如何从数据包原型字段上的数字中获取带有 IP 协议名称的字符串?
例如,将 6 转换为“TCP”。
【问题讨论】:
标签: python tcp protocols scapy pyshark
使用 PyShark,如何从数据包原型字段上的数字中获取带有 IP 协议名称的字符串?
例如,将 6 转换为“TCP”。
【问题讨论】:
标签: python tcp protocols scapy pyshark
您可以从 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'
【讨论】:
这是使用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...
【讨论】: