最近一直在使用做流量分析,今天把 pyshark部分做一个总结。
Python 的 pyshark库可以方便的抓包与解析包,无奈资料很少,官方例子有限,大神博客很少提及, 经过一番尝试后,总结以下几点用法以便大家以后使用。
from scapy.all import *
ospf_packet = (
IP(dst="224.0.0.5") / # OSPF AllSPFRouters multicast address
UDP(sport=89, dport=89) /
OSPFv2(
version=2,
type=1, # Hello packet
router_id=10, # Example Router ID
area_id=0x00000001, # Example Area ID
checksum=None, # Will be calculated automatically
au_type=0, # Authentication Type, usually 0 for no authentication
hello_interval=10, # Hello Interval
options="E",
priority=1, # Router Priority
dead_interval=40 # Dead Interval
)
)
import pyshark
def analyze_isis_packets(interface='eth0'):
"""
分析IS-IS协议的数据包。
参数:
- interface: 要监听的网络接口名,默认为'eth0'
"""
print("开始捕获IS-IS数据包...")
capture_filter = 'proto isis' # 捕获IS-IS协议的数据包
capture = pyshark.LiveCapture(interface=interface, display_filter=capture_filter)
# 循环处理捕获到的每一个IS-IS数据包
for packet in capture.sniff_continuously(packet_count=0): # 不限制捕获包的数量
try:
# 由于IS-IS的具体字段可能根据实际数据包内容有所不同,
# 下面的示例仅展示了如何访问IS-IS头的一些基本字段。
# 请根据需要调整,查阅具体的IS-IS协议字段。
isis_layer = packet.isis
print(f"IS-IS Packet:")
print(f" Source ID: {isis_layer.source_id}")
print(f" PDU Type: {isis_layer.pdu_type}")
# 根据需要添加更多字段的解析
except AttributeError:
# 可能会遇到非IS-IS数据包,这里简单忽略
pass
print("捕获结束.")
# 调用函数,开始分析
analyze_isis_packets('以太网 5') # 请替换为你的实际网络接口名