Skip to content

Instantly share code, notes, and snippets.

@kellyjonbrazil
Created August 3, 2021 22:23
Show Gist options
  • Save kellyjonbrazil/3cf4b4f58f5767d5f71ef89a89962263 to your computer and use it in GitHub Desktop.
Save kellyjonbrazil/3cf4b4f58f5767d5f71ef89a89962263 to your computer and use it in GitHub Desktop.
Generate graphviz dot graph from traceroute command output
#!/usr/bin/env python3
#
# Convert traceroute command output to a graphviz DOT graph
# Use `jc` to convert `traceroute` output to JSON before piping to tr2dot.py
#
# Version 1.0
# Kelly Brazil ([email protected])
#
# Requires graphviz (pip3 install graphviz)
#
# Usage:
# $ traceroute -m 5 www.example.com | jc --traceroute | ./tr2dot.py
# or
# $ jc traceroute -m 5 www.example.com | ./tr2dot.py
import sys
import json
import graphviz
_ = json.loads(sys.stdin.read())
# dict to dot
dest = _.get("destination_ip", None)
dot = graphviz.Digraph(comment=f'Traceroute to {dest}')
# nodes
for hop in _['hops']:
if hop['probes']:
ip_set = set()
for probe in hop['probes']:
ip_set.add(probe['ip'])
dot.node(str(hop['hop']), ', '.join(ip_set))
# edges
edge_list = []
for hop in _['hops']:
if hop['probes']:
edge_list.append(str(hop['hop']))
dot_edge_list = []
for i, v in enumerate(edge_list):
try:
first = v
second = edge_list[i + 1]
dot_edge_list.append(f'{first}{second}')
except Exception:
pass
dot.edges(dot_edge_list)
dot.render('traceroute.gv', view=True)
@kellyjonbrazil
Copy link
Author

kellyjonbrazil commented Aug 3, 2021

This is a simple python script to convert the output of the traceroute command to a DOT graph, which can be rendered several different ways. Uses jc to first convert the output of the traceroute command to JSON for easier parsing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment