gpt-4-0314· openai
Suzhen/CodeChat
帮我生成Python代码,通过向局域网内发送lldp数据包,然后基于收到的回应生成网络拓扑图
- User
帮我生成Python代码,通过向局域网内发送lldp数据包,然后基于收到的回应生成网络拓扑图
- Assistant
这是一个利用Scapy库构造LLDP数据包并在局域网内发送的Python代码示例。你需要首先在你的环境中安装Scapy库。你可以通过运行
pip install scapy进行安装。接下来,我们将构造一个LLDP数据包并将其发送到局域网内,然后使用收到的回应生成网络拓扑图。import socket from scapy.all import * from scapy.layers.l2 import Ether, Dot1Q, LLDPDU, LLDPDUChassisID, LLDPDUPortID, LLDPDUTimeToLive import matplotlib.pyplot as plt import networkx as nx def send_lldp_packet(interface, ttl=120): src_mac = get_if_hwaddr(interface) packet = Ether(dst="01:80:c2:00:00:0e", src=src_mac) packet /= Dot1Q(vlan=0) packet /= LLDPDU() packet /= LLDPDUChassisID(subtype=4, id=src_mac) packet /= LLDPDUPortID(subtype=3, id=interface) packet /= LLDPDUTimeToLive(ttl=ttl) sendp(packet, iface=interface, verbose=False) def handle_lldp_packet(packet): if packet.haslayer('LLDPDU'): lldp_id = packet['LLDPDUChassisID'].id src_mac = packet[Ether].src port_id = packet['LLDPDUPortID'].id return (lldp_id, src_mac, port_id) return None def get_lldp_responses(timeout=10): responses = [] packet_filter = "ether proto 0x88cc" sniff(filter=packet_filter, prn=lambda x: responses.append(handle_lldp_packet(x)), timeout=timeout) return responses def create_topology_graph(responses): G = nx.Graph() for r in responses: if r: lldp_id, src_mac, port_id = r if not G.has_node(lldp_id): G.add_node(lldp_id) G.add_edge(lldp_id, src_mac, port=port_id) return G def draw_topology_graph(G): pos = nx.kamada_kawai_layout(G) nx.draw(G, pos, with_labels=True, node_color="lightblue", font_size=8) plt.title("Network Topology") plt.show() if __name__ == "__main__": interface = "eth0" # 更改为你的网络接口名称 send_lldp_packet(interface) responses = get_lldp_responses() G = create_topology_graph(responses) draw_topology_graph(G)