Free tech learning for everyone, from basics to pro

Network AutomationNetworking SecurityIntermediate

Project: discovering your network topology with LLDP and Python

In short: Many networks lack accurate diagrams. This project writes a Python script that starts from one switch, reads its LLDP neighbours, then connects to each neighbour and repeats, keeping track of visited devices. The result is a list of devices and links that can be exported to CSV, compared with documentation or loaded into a source of truth.

The goal

Given one starting device and credentials, find every connected network device and the links between them. LLDP (or Cisco's CDP) tells each device about its directly connected neighbours, including their names, management addresses and ports.

Crawling the network with LLDPSeed devicestart pointReadneighboursLLDP / CDPQueue newnot yetvisitedRepeatuntil noneleftOutputinventory andlinks
Figure 1. Starting from one device, neighbour data reveals the rest of the network.

Preparation

  • Enable LLDP on all network devices (lldp run on Cisco IOS).
  • Make sure neighbours advertise a management address.
  • Use a read-only automation account.
  • Install: pip install netmiko ntc-templates.

The script

import csv
import os
from collections import deque
from netmiko import ConnectHandler

SEED = "10.0.0.1"
USER, PASS = os.environ["NET_USER"], os.environ["NET_PASS"]

def get_neighbours(ip):
    dev = {"device_type": "cisco_ios", "host": ip,
           "username": USER, "password": PASS, "timeout": 15}
    with ConnectHandler(**dev) as conn:
        hostname = conn.find_prompt().rstrip("#>")
        nbrs = conn.send_command("show lldp neighbors detail", use_textfsm=True)
    return hostname, nbrs if isinstance(nbrs, list) else []

visited, links, failed = set(), [], []
queue = deque([SEED])

while queue:
    ip = queue.popleft()
    if ip in visited:
        continue
    visited.add(ip)
    try:
        host, nbrs = get_neighbours(ip)
    except Exception as exc:
        failed.append((ip, str(exc)))
        continue
    for n in nbrs:
        links.append([host, n.get("local_interface"),
                      n.get("neighbor_name"), n.get("neighbor_interface")])
        mgmt = n.get("mgmt_address")
        if mgmt and mgmt not in visited:
            queue.append(mgmt)

with open("links.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["device", "local_port", "neighbour", "neighbour_port"])
    w.writerows(links)

print(f"Visited {len(visited)} devices, {len(links)} links, {len(failed)} failed")

TextFSM field names depend on the template version and platform; print one neighbour record first and adjust the keys. Each link appears twice (once from each side); remove duplicates if needed.

Improvements

  • Filter neighbours so the crawl does not try to log in to phones, access points or servers (check the system capabilities field).
  • Detect platform type from the neighbour's description and set device_type accordingly.
  • Add concurrency with a thread pool and a sensible worker limit.
  • Limit the crawl to allowed address ranges.
  • Export to a diagram tool or load devices and cables into NetBox.

Real-world example: the forgotten switch

Running the discovery script at a factory found 14 switches, but the documentation listed 12. One unknown switch was an unmanaged-looking device in a production area that actually had LLDP enabled and default credentials. It was brought under management, and the documentation was finally corrected.

Practice

Why does the script keep a visited set?
To avoid connecting to the same device repeatedly and looping forever.
What information from LLDP is needed to continue the crawl?
The neighbour's management address.
Name one improvement to make the crawler safer or faster.
Any of: filter non-network neighbours, limit address ranges, detect platform types, add limited concurrency.

Key takeaways

  • LLDP neighbour data lets a script discover the network from one seed device.
  • A queue and visited set give a safe breadth-first crawl.
  • Record links and failures, and export the results.
  • Filter neighbours, limit scope and adjust parser fields for your platforms.
Tracks your learning on this device only. See your progress on the learning paths.
Verified author✓ Valid
Issued to
Mohamed Fayas
Role
Founder of FM TecHub
Credentials
CCNABTEC HND Network EngineeringBEng (Hons) Computer Networking & Cloud Security
Issuer
FM TecHub · fmtechub.com

He writes practical, plain-English guides on networking, security and cloud.

More about the author →

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Email updates: coming soon

New notes, tools and security news from FM TecHub by email, explained simply. Free. We're not collecting email addresses yet; see our privacy policy.

PortServiceStatus
SMTP/25Email updatesopening soon

Meanwhile, stay connected: