Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

请帮我生成Python代码,电脑在指定的端口上广播lldp数据帧来探测网络内的其它设备,基于收到的消息来绘制网络的拓扑图

  1. User

    请帮我生成Python代码,电脑在指定的端口上广播lldp数据帧来探测网络内的其它设备,基于收到的消息来绘制网络的拓扑图

  2. Assistant

    以下是一个示例代码,需要安装 scapy 库来运行:

    from scapy.all import *
    
    def get_lldp_info(pkt):
        if pkt.haslayer(LLDPDU):
            lldpdu = pkt[LLDPDU]
            chassis_id = lldpdu.get_tlv_val(1).decode("utf-8")
            port_id = lldpdu.get_tlv_val(2).decode("utf-8")
            ttl = lldpdu.get_tlv_val(3)
            return (chassis_id, port_id, ttl)
    
    def send_lldp_broadcast(interface):
        ether = Ether(dst="01:80:c2:00:00:0e")
        chassis_id_tl = LLDPChassisID(subtype=7, id=bytes(BPFProgram(interface=interface).filter[0].bh_mac))
        port_id_tl = LLDPPortID(subtype=7, id=str(interface).encode())
        ttl_tl = LLDPDUTimeToLive(seconds=120)
        lldpdu = LLDPDU(tlvs=[chassis_id_tl, port_id_tl, ttl_tl])
        pkt = ether / lldpdu
        sendp(pkt, iface=interface, loop=1)
    
    def main():
        topology = {}
        interfaces = get_windows_if_list() if sys.platform == "win32" else get_if_list()
        print("Available network interfaces:")
        for i in range(len(interfaces)):
            print(f"{i}: {interfaces[i]}")
        interface_idx = int(input("Choose an interface to broadcast LLDP frames: "))
        interface = interfaces[interface_idx]
        try:
            while True:
                send_lldp_broadcast(interface)
                pkt = sniff(iface=interface, timeout=1, filter="ether dst 01:80:c2:00:00:0e")
                for p in pkt:
                    info = get_lldp_info(p)
                    if info:
                        chassis_id, port_id, ttl = info
                        if chassis_id not in topology:
                            topology[chassis_id] = []
                        topology[chassis_id].append(port_id)
                print("\nNetwork topology:")
                for i, (chassis_id, port_ids) in enumerate(topology.items()):
                    print(f"{i+1}. {chassis_id}")
                    for port_id in port_ids:
                        print(f"   {port_id}")
        except KeyboardInterrupt:
            pass
    
    if __name__ == "__main__":
        main()
    

    这个代码使用 scapy 库来发送和接收 LLDP 数据帧,然后解析数据帧中的信息来绘制网络拓扑。可以在运行时选择一个网络接口来广播 LLDP 数据帧,然后在控制台中输出网络拓扑的信息。需要注意的是,当运行此程序时需要管理员权限才能启动。