Advertisement
Open Source Projects by Phil Schwartz

Building A Python Network Diagram Generator From Routing Tables

A routing table is a compact description of how packets leave a host or router, but it is difficult to understand when viewed as a long command-line listing. A Python-based network diagram generator can turn those routes into a visual map of interfaces, next hops, subnets and probable paths.

The project suits developers who work with Linux administration, infrastructure automation or open-source diagnostic tools. It can begin as a small script that reads ip route output and grow into a reusable application that accepts routing information from servers, firewalls and network appliances.

For Australian teams, this kind of utility can make distributed environments easier to inspect. A business operating between Sydney, Melbourne and Perth may need to compare local office gateways, cloud connections and NBN-based links without manually drawing a diagram every time the network changes.

Define The Diagram’s Purpose

Before writing a parser, decide what the generated network topology should communicate. A basic diagram might show each routing-table entry as a directed edge from a host to a gateway. A richer version could group routes by interface, identify directly connected networks and distinguish default routes from specific prefixes.

Routing tables do not contain every fact required for a perfect physical map. They usually reveal logical forwarding relationships rather than cable layouts, switch ports or firewall policies. The generator should therefore describe its output as a routing or layer-three topology diagram, rather than claiming to reconstruct the entire network.

Useful diagram elements include destination CIDR blocks, next-hop addresses, interface names, route metrics and route sources. A default route such as default via 192.168.1.1 dev eth0 can become a clear edge towards the gateway, while 192.168.1.0/24 dev eth0 can identify a directly attached subnet.

Collect Routing Data Safely

On a Linux system, the most reliable starting point is the ip route command from the iproute2 package. Python can invoke it with subprocess.run, capture standard output and reject non-zero exit codes. JSON output from ip -j route is preferable where available because it avoids fragile text parsing and provides structured fields.

A generator may later support /proc/net/route, route -n, BSD tools, cloud APIs and network devices accessed through Netmiko or NAPALM. Each source should be converted into the same internal representation, such as a route object containing a destination network, gateway, device, metric, protocol and scope.

Collection needs appropriate permissions and careful handling of credentials. For a managed service provider in Brisbane or Adelaide, an automated job may inspect many customer environments. Secrets should be loaded from an operating-system key store or a protected environment, never embedded in source code or written into diagram metadata.

Parse Prefixes With Python’s Standard Library

The ipaddress module provides the core functionality for validating and comparing IPv4 and IPv6 networks. ipaddress.ip_network can normalise a prefix, while ip_address can validate a gateway or host address. Normalisation prevents equivalent entries such as 10.0.0.0/24 and 10.0.0.12/24 from appearing as separate networks.

A parser should handle routes that have no gateway, including connected routes and loopback entries. It should also tolerate optional attributes such as src, proto, scope, metric, table and onlink. Unknown fields should be retained when practical or ignored predictably, rather than causing the entire import to fail.

Route selection deserves explicit rules. If several entries match a destination, the longest-prefix match generally wins, followed by route preference and metric according to the platform. A visualiser does not always need to simulate forwarding, but exposing overlapping prefixes and competing gateways can reveal configuration mistakes.

Build A Graph Model

NetworkX is a practical choice for an in-memory graph model. Nodes can represent routers, interfaces, hosts and networks, while edges can represent forwarding relationships. A simpler model uses route entries as edges from an observed device to a destination prefix, with labels for the next hop and interface.

For large environments, avoid creating a node for every address in a subnet. A /16 network can contain thousands of possible hosts, yet its routing significance may be captured by a single CIDR node. Grouping by prefix keeps the diagram readable and improves rendering speed.

The model should carry provenance. Each route can record the source hostname, collection time and command or API used. This makes it possible to compare diagrams over time and explain why a route appears. It also helps an administrator distinguish a stale export from a current route learned through OSPF or BGP.

Render Readable Network Maps

Graphviz provides strong layout engines for directed network diagrams, and Python can access it through packages such as graphviz or pygraphviz. SVG is usually the best default because it remains sharp when zoomed and can be embedded in documentation. PNG output is useful for tickets, dashboards and quick status reports.

Visual encoding should be restrained. Use different shapes for routers, interfaces and networks, and reserve colours for meaningful states such as a default route, a failed collection or a conflicting prefix. Labels should include enough information to support troubleshooting without turning every edge into an unreadable paragraph.

A useful implementation can produce both a detailed and a simplified view. The detailed view includes metrics and route protocols for engineers, while the summary view collapses repeated interfaces and shows only major paths. This is particularly helpful for teams supporting a mixture of cloud workloads, office networks and remote workers across Australia.

Test, Secure And Operate The Tool

Testing should cover ordinary IPv4 routes, IPv6 prefixes, unreachable routes, duplicate entries, missing gateways and malformed command output. Fixtures containing representative ip -j route responses make parser tests repeatable. Property-based tests can generate valid and invalid prefixes to find edge cases that hand-written examples miss.

The utility should provide clear command-line options, structured logging and an exit status suitable for CI pipelines. A scheduled job might collect routes overnight, write a timestamped SVG and compare the graph with the previous version. A sudden new default gateway or disappearing VPN prefix can then trigger an alert before users report an outage.

Network diagrams can expose internal addresses, hostnames and infrastructure relationships. Organisations subject to the Australian Privacy Act 1988 should assess whether collected data can be linked to individuals, particularly when diagrams include employee devices or home-office details. Access controls, retention limits and encryption are sensible safeguards, while Essential Eight practices provide a useful operational baseline for many Australian businesses.

Practical Features Worth Prioritising

A small first release is easier to validate than an ambitious network-management platform. Start with local Linux route collection, IPv4 and IPv6 parsing, Graphviz export and a documented data format. Add remote collection only after the diagram accurately represents known test networks.

The following features provide a strong development path:

A well-designed generator can remain useful even when it does not understand every vendor-specific command. Its value comes from turning inconsistent routing information into a common, searchable and reviewable model. That makes the project a natural companion to Linux utilities and open-source administration tools, while giving developers a practical way to explore network automation in Python.