Skip to content

JSON API Reference

Thomas Mangin edited this page Oct 3, 2026 · 12 revisions

JSON API Reference

Complete reference for ExaBGP's JSON-encoded messages


Table of Contents


Overview

The JSON encoder provides structured BGP messages to your API program via STDIN.

Configuration: Define the helper in a top-level process block, then attach it and subscribe to events in the neighbor's api block. Session state changes use neighbor-changes directly under api; incoming message subscriptions belong under receive.

process receive-routes {
    run /etc/exabgp/api/receive.py;
    encoder json;
}

neighbor 192.168.1.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65000;

    api {
        processes [ receive-routes ];
        neighbor-changes;  # Receive session state changes
        receive {
            parsed;  # Receive parsed BGP messages
            update;  # Receive route updates
        }
    }
}

Usage in your program:

import sys
import json

while True:
    line = sys.stdin.readline()
    if not line:
        break

    message = json.loads(line)
    # STDOUT carries commands to ExaBGP, so anything else goes to STDERR
    print(f"Message type: {message['type']}", file=sys.stderr)

Format:

  • One JSON object per line
  • UTF-8 encoded
  • No newlines within JSON (compact format)
  • Continuous stream (process must read continuously)

Message Structure

Common Fields (All Messages)

Every JSON message carries the same envelope:

{
  "exabgp": "6.0.0",
  "time": 1790493340.398976,
  "host": "a-hostname",
  "pid": 90686,
  "ppid": 90683,
  "counter": 3,
  "type": "state",
  "neighbor": {}
}

exabgp is the version of the JSON format, not of the software. There are two writers, chosen by exabgp_api_version, which defaults to 6:

  • 6.0.0 from the v6 writer, which is what you get unless you ask otherwise
  • 4.0.1 from the v4 writer, selected with exabgp_api_version=4, which logs a deprecation warning and which src/exabgp/version.py marks frozen

Every example on this page is v6. Be aware when reading captures under qa/ that the functional test harness sets exabgp_api_version=4, so what it records is the legacy format.

So do not parse it as a software version, and do not expect it to change when ExaBGP is upgraded. Decide which format you are reading from this field, nothing else.

time is a float of seconds since the epoch. counter increments per message on the process, so a gap means a message was dropped somewhere. pid is ExaBGP, ppid its parent.

Message types:

  • update - route announcement or withdrawal
  • state - the session reached connected, up or down (neighbor-changes)
  • fsm - the finite state machine moved, which is finer grained than state (fsm)
  • negotiated - what the two ends agreed after the OPEN exchange (negotiated)
  • notification - a BGP NOTIFICATION was sent or received
  • keepalive - a KEEPALIVE was sent or received
  • open - an OPEN was sent or received
  • refresh - a ROUTE-REFRESH was sent or received
  • signal - a signal was delivered to the process (signal)

The name in brackets is the api {} option which turns that report on. Nothing is reported unless it is asked for.

direction appears on any message which came from or went to the wire, and its values are receive and send. The json: lines recorded in qa/ show in instead, because those captures are written by the test peer rather than by ExaBGP.


Message Types

Each example below was captured from a running session by giving the neighbour every reporting option and recording what the process received. To reproduce them, add to a neighbour:

api {
    processes [ your-process ];
    neighbor-changes;
    negotiated;
    fsm;
    send    { parsed; update; }
    receive { parsed; open; update; notification; keepalive; }
}

UPDATE

Covered in detail under UPDATE Messages. The shape is neighbor.message.update, with attribute beside announce and withdraw.


STATE

neighbor-changes reports the session reaching a state. The values are connected, up and down, and a down also carries a reason.

{
  "exabgp": "6.0.0",
  "time": 1790493708.683239,
  "host": "thomasmangin-J44N2XRXNR-770.local",
  "pid": 91662,
  "ppid": 91659,
  "counter": 3,
  "type": "state",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "state": "connected"
  }
}

FSM

fsm reports the BGP finite state machine instead, which is finer grained. One session produced IDLE, ACTIVE, CONNECT, OPENSENT, OPENCONFIRM and ESTABLISHED.

{
  "exabgp": "6.0.0",
  "time": 1790493708.682559,
  "host": "thomasmangin-J44N2XRXNR-770.local",
  "pid": 91662,
  "ppid": 91659,
  "counter": 1,
  "type": "fsm",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "state": "ACTIVE"
  }
}

NOTIFICATION

code and subcode are the RFC 4271 error code and subcode, data is the hex of the notification data, and message is that data as text when it is text. This holds for a NOTIFICATION received as well as one sent; before 6.0.0 a received one had a display string in data. The neighbour block is the same as in every other message, so only the notification member is shown:

{
  "notification": {
    "code": 6,
    "subcode": 2,
    "data": "0x1761646D696E6973747261746976652073687574646F776E",
    "message": "\u0017administrative shutdown"
  }
}

KEEPALIVE

{
  "exabgp": "6.0.0",
  "time": 1790493708.6846468,
  "host": "thomasmangin-J44N2XRXNR-770.local",
  "pid": 91662,
  "ppid": 91659,
  "counter": 9,
  "type": "keepalive",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive"
  }
}

OPEN

The capabilities the peer sent, as ExaBGP read them. Each is keyed by its name, with its capability code inside as code; an OPEN ExaBGP sends is reported the same way.

{
  "exabgp": "6.0.0",
  "time": 1790493708.68431,
  "host": "thomasmangin-J44N2XRXNR-770.local",
  "pid": 91662,
  "ppid": 91659,
  "counter": 6,
  "type": "open",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive",
    "open": {
      "version": 4,
      "asn": 1,
      "hold_time": 180,
      "router_id": "1.2.3.5",
      "capabilities": {
        "multiprotocol": {
          "code": 1,
          "name": "multiprotocol",
          "families": [
            "ipv4/unicast"
          ]
        },
        "asn4": {
          "code": 65,
          "name": "asn4",
          "asn4": 1
        },
        "extended-message": {
          "code": 6,
          "name": "extended-message",
          "size": 65535
        }
      }
    }
  }
}

NEGOTIATED

negotiated reports what the two ends agreed on, once the OPEN exchange is done.

{
  "exabgp": "6.0.0",
  "time": 1790493708.684469,
  "host": "thomasmangin-J44N2XRXNR-770.local",
  "pid": 91662,
  "ppid": 91659,
  "counter": 7,
  "type": "negotiated",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "negotiated": {
      "message_size": 65535,
      "hold_time": 180,
      "asn4": true,
      "multisession": false,
      "operational": false,
      "refresh": "absent",
      "families": [
        "ipv4 unicast"
      ],
      "nexthop": [],
      "add_path": {
        "send": [],
        "receive": []
      }
    }
  }
}

UPDATE Messages

Every example below was taken from a message this repository records and tests, and the file it came from is named under each one. To regenerate any of them, read the json: line of that capture, or decode its raw: line with ./sbin/exabgp decode. The captures say "direction": "in"; the examples show "receive", which is what a program receives.

The shape is the same for every family:

neighbor.message.update.attribute          the path attributes, once for the message
neighbor.message.update.announce.<family>   next hop -> list of NLRI sharing it
neighbor.message.update.withdraw.<family>   list of NLRI, with no next hop

A family key always contains a space, as in ipv4 unicast or l2vpn vpls.

IPv4 Unicast Announcement

The family key holds one entry per next hop, and each entry is the list of NLRI which share it. The path attributes are a sibling of announce, not a member of a route, because one UPDATE carries one attribute set for every NLRI in it.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "local-preference": 100
        },
        "announce": {
          "ipv4 unicast": {
            "101.1.101.1": [
              {
                "nlri": "1.1.0.0/24"
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/api/api-ack-control.ci.


IPv4 Unicast Withdrawal

A withdrawal has no next hop to group by, so the family key holds the list of NLRI directly. RFC 4760 section 3 also means there is nothing to say about attributes here.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive",
    "message": {
      "update": {
        "withdraw": {
          "ipv4 unicast": [
            {
              "nlri": "1.1.0.0/24"
            }
          ]
        }
      }
    }
  }
}

Recorded in qa/api/api-add-remove.ci.


IPv6 Unicast

Identical in shape to IPv4. The family key is ipv6 unicast, with a space.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 65512,
      "peer": 65512
    },
    "router-id": "10.0.0.139",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "local-preference": 100
        },
        "announce": {
          "ipv6 unicast": {
            "::1": [
              {
                "nlri": "::1/128"
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/api/api-check.ci.


FlowSpec

A flow NLRI renders its components as named lists, and carries a string which is the rule as the configuration grammar would write it. RFC 8955 section 4 keeps the next hop out of a flow advertisement, so the next hop key is no-nexthop.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "local-preference": 100,
          "extended-community": [
            {
              "value": 9225060887780392960,
              "string": "rate-limit:1"
            }
          ]
        },
        "announce": {
          "ipv4 flow": {
            "no-nexthop": [
              {
                "destination-ipv4": [
                  "170.170.170.170/32"
                ],
                "source-ipv4": [
                  "170.170.170.170/32"
                ],
                "string": "flow destination-ipv4 170.170.170.170/32 source-ipv4 170.170.170.170/32"
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/api/api-broken-flow.ci.


L3VPN

A VPN NLRI adds rd and label to the route object.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "as-path": {
            "0": {
              "element": "as-sequence",
              "value": [
                100,
                500
              ]
            }
          },
          "local-preference": 100,
          "originator-id": "10.0.99.12",
          "extended-community": [
            {
              "value": 562949953421312,
              "string": "target:0:0"
            }
          ]
        },
        "announce": {
          "ipv4 mpls-vpn": {
            "10.0.99.12": [
              {
                "nlri": "128.0.64.0/18",
                "label": [
                  [
                    110,
                    1761
                  ]
                ],
                "rd": "63333:100"
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/api/api-attributes-vpn.ci.


Labelled Unicast

RFC 8277. The route object carries its label stack.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 65000,
      "peer": 65000
    },
    "router-id": "198.51.100.200",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "local-preference": 100,
          "bgp-prefix-sid": {
            "sr-label-index": 777
          }
        },
        "announce": {
          "ipv4 nlri-mpls": {
            "198.51.100.1": [
              {
                "nlri": "198.51.100.100/32",
                "label": [
                  [
                    800001,
                    12800017
                  ]
                ]
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/encoding/conf-prefix-sid.ci.


VPLS

RFC 4761. The endpoint fields sit in the route object beside the route distinguisher.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "as-path": {
            "0": {
              "element": "as-sequence",
              "value": [
                30740,
                30740,
                30740,
                30740,
                30740,
                30740,
                30740
              ]
            }
          },
          "med": 2000,
          "local-preference": 100,
          "community": [
            [
              54591,
              123
            ]
          ],
          "originator-id": "192.168.22.1",
          "cluster-list": [
            "3.3.3.3",
            "192.168.201.1"
          ],
          "extended-community": [
            {
              "value": 797416513077254,
              "string": "target:54591:6"
            },
            {
              "value": 9226207677441114223,
              "string": "l2info:19:0:1500:111"
            }
          ]
        },
        "announce": {
          "l2vpn vpls": {
            "192.168.201.1": [
              {
                "rd": "192.168.201.1:123",
                "endpoint": 5,
                "base": 10702,
                "offset": 1,
                "size": 8
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/api/api-vpls.ci.


Multicast VPN

RFC 6514. An mcast-vpn route has no single string which names it, so it renders its own fields plus code, name and the raw wire bytes.

{
  "exabgp": "6.0.0",
  "type": "update",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 65000,
      "peer": 65000
    },
    "router-id": "32.32.32.32",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "local-preference": 100,
          "extended-community": [
            {
              "value": 72832373356232709,
              "string": "target:192.168.94.12:5"
            }
          ]
        },
        "announce": {
          "ipv4 mcast-vpn": {
            "10.10.6.3": [
              {
                "code": 6,
                "parsed": true,
                "raw": "06160000FDE80001869F0000FDE8200A63C70120EFFBFFE4",
                "name": "C-Multicast Shared Tree Join route",
                "rd": "65000:99999",
                "source-as": "65000",
                "source": "10.99.199.1",
                "group": "239.251.255.228"
              }
            ]
          }
        }
      }
    }
  }
}

Recorded in qa/api/api-mvpn.ci.


Changed in 6.0.0

Three things change shape against 5.x. Outside BGP-LS, UPDATE messages are not among them.

  • OPEN capabilities are keyed by their name, where a received OPEN used their code ("65"). The code is inside each capability as code, so a program can still match on it. See OPEN.
  • The data of a received NOTIFICATION is its Data field in hex, as for one ExaBGP sends; the text is in message. See NOTIFICATION.
  • BGP-LS members which a peer may repeat are arrays. See BGP-LS JSON API Changes.

The first two are API 6. A program on API 4, which writes the 5.x commands or runs with exabgp_api_version=4, is written what 5.x wrote: the capabilities under their code, and the readable text of a NOTIFICATION as its data.

New Keys in 6.0.0

Two keys were added, and neither is a rename or a change of type.

link-local-next-hop

RFC 2545 lets an MP_REACH_NLRI for IPv6 carry a 32 octet Next Hop: a global address followed by a link-local one. ExaBGP decoded both halves and then threw the link-local away, so a 32 octet next hop and a plain 16 octet one produced identical JSON. The link-local address now appears as link-local-next-hop on the route entry. RFC 8950 pairs report theirs the same way.

{
  "type": "update",
  "neighbor": {
    "message": {
      "update": {
        "attribute": { "origin": "igp", "local-preference": 100 },
        "announce": {
          "ipv6 unicast": {
            "2001:db8::ffff": [
              { "nlri": "2001:db8:1::1/128", "link-local-next-hop": "fe80::1" }
            ]
          }
        }
      }
    }
  }
}

next-hop keeps meaning the global address, which is what RFC 2545 has always said it means. The key is absent when the peer sent a 16 octet next hop, so test for its presence rather than for a value:

link_local = route.get('link-local-next-hop')  # None on a 16 octet next hop

enlp-name

The SR Policy ENLP sub-TLV rendered as a bare number, "enlp": 4, while the logs printed the name. The number is unchanged and stays an integer; the name arrives beside it as enlp-name.

This is a fragment of the attribute block, not a whole message:

{
  "tunnel-encap": {
    "sr-policy": {
      "preference": 400,
      "enlp": 4,
      "enlp-name": "no-push"
    }
  }
}

STATE Messages

neighbor-changes reports three states. connected when the TCP session is established, up when BGP reaches ESTABLISHED, and down when it ends. Only down carries a reason.

Session UP

{
  "exabgp": "6.0.0",
  "time": 1790493708.686909,
  "host": "thomasmangin-J44N2XRXNR-770.local",
  "pid": 91662,
  "ppid": 91659,
  "counter": 11,
  "type": "state",
  "neighbor": {
    "address": {
      "local": "127.0.0.1",
      "peer": "127.0.0.1"
    },
    "asn": {
      "local": 1,
      "peer": 1
    },
    "router-id": "1.2.3.4",
    "state": "up"
  }
}

Captured from a running session.

Session DOWN

A down adds reason, which is the text ExaBGP would log for the same event:

{
  "type": "state",
  "neighbor": {
    "address": {
      "local": "no-nexthop",
      "peer": "no-nexthop"
    },
    "asn": {
      "local": 0,
      "peer": 0
    },
    "state": "down",
    "reason": "Cease - administrative reset"
  }
}

The neighbour block is the same as above; the addresses here are absent because this one was produced by calling the writer rather than by running a session.


NOTIFICATION Messages

A NOTIFICATION is reported at neighbor.notification, which is not inside neighbor.message. Four members:

  • code and subcode, the RFC 4271 error code and subcode
  • data, the notification data as hex with an 0x prefix
  • message, that data decoded as text when it is text

direction says whether the NOTIFICATION was received or sent, so a session ExaBGP itself tears down reports one with "direction": "send".

{
  "type": "notification",
  "neighbor": {
    "notification": {
      "code": 6,
      "subcode": 2,
      "data": "0x1761646D696E6973747261746976652073687574646F776E",
      "message": "\u0017administrative shutdown"
    }
  }
}

RFC 4271 section 4.5 and its IANA registry hold the code and subcode values. 6/2 above is Cease with subcode Administrative Shutdown.


Parsing Patterns

Basic Parser

#!/usr/bin/env python3
import sys
import json

while True:
    line = sys.stdin.readline()
    if not line:
        break

    try:
        msg = json.loads(line)

        # Route update
        if msg['type'] == 'update':
            handle_update(msg)

        # Session state
        elif msg['type'] == 'state':
            handle_state(msg)

        # Notification
        elif msg['type'] == 'notification':
            handle_notification(msg)

    except json.JSONDecodeError as e:
        print(f"JSON parse error: {e}", file=sys.stderr)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)

Parse IPv4 Unicast Routes

def handle_update(msg):
    """Process UPDATE messages"""
    if 'update' not in msg['neighbor']['message']:
        return

    update = msg['neighbor']['message']['update']

    # The attributes are shared by every route of the message
    med = update.get('attribute', {}).get('med', 0)

    # Announced routes: next hop -> list of routes
    if 'announce' in update:
        if 'ipv4 unicast' in update['announce']:
            next_hops = update['announce']['ipv4 unicast']
            for nexthop, routes in next_hops.items():
                for route in routes:
                    if 'nlri' not in route:
                        continue  # an End-of-RIB marker
                    print(f"[ANNOUNCE] {route['nlri']} via {nexthop} (MED {med})",
                          file=sys.stderr)

    # Withdrawn routes: list of routes
    if 'withdraw' in update:
        if 'ipv4 unicast' in update['withdraw']:
            for route in update['withdraw']['ipv4 unicast']:
                print(f"[WITHDRAW] {route['nlri']}", file=sys.stderr)

Parse FlowSpec Rules

def handle_flowspec(msg):
    """Process FlowSpec updates"""
    if 'update' not in msg['neighbor']['message']:
        return

    update = msg['neighbor']['message']['update']

    # The action is an extended community, shared by every rule of the message
    action = 'unknown'
    for comm in update.get('attribute', {}).get('extended-community', []):
        text = comm['string']  # for example "rate-limit:1000" ("rate-limit:0" discards) or "redirect:65001:100"
        if text.startswith(('rate-limit', 'redirect')):
            action = text

    if 'announce' in update:
        if 'ipv4 flow' in update['announce']:
            # a flow route has no next hop, its key is "no-nexthop"
            for rules in update['announce']['ipv4 flow'].values():
                for flow in rules:
                    if 'string' not in flow:
                        continue  # an End-of-RIB marker
                    # Parse match conditions, each a list
                    dest = flow.get('destination-ipv4', ['any'])[0]
                    src = flow.get('source-ipv4', ['any'])[0]
                    port = flow.get('destination-port', ['any'])[0]
                    proto = flow.get('protocol', ['any'])[0]

                    print(f"[FLOWSPEC] {src} -> {dest}:{port} proto:{proto} action:{action}",
                          file=sys.stderr)

Parse Session State

def handle_state(msg):
    """Process STATE messages"""
    peer = msg['neighbor']['address']['peer']
    state = msg['neighbor']['state']

    if state == 'up':
        print(f"[STATE] BGP session with {peer} is UP", file=sys.stderr)
    elif state == 'down':
        reason = msg['neighbor'].get('reason', 'unknown')
        print(f"[STATE] BGP session with {peer} is DOWN: {reason}",
              file=sys.stderr)
    else:
        print(f"[STATE] BGP session with {peer}: {state}", file=sys.stderr)

Track Announced Routes

import json
import sys


class RouteTracker:
    def __init__(self):
        self.routes = {}  # prefix -> (next hop, attributes)

    def update(self, msg):
        if 'update' not in msg['neighbor']['message']:
            return

        update = msg['neighbor']['message']['update']
        attributes = update.get('attribute', {})

        # Add/update announced routes: next hop -> list of routes
        if 'announce' in update:
            if 'ipv4 unicast' in update['announce']:
                for nexthop, routes in update['announce']['ipv4 unicast'].items():
                    for route in routes:
                        if 'nlri' not in route:
                            continue  # an End-of-RIB marker
                        prefix = route['nlri']
                        self.routes[prefix] = (nexthop, attributes)
                        print(f"[TRACKER] Added {prefix}, total routes: {len(self.routes)}",
                              file=sys.stderr)

        # Remove withdrawn routes: list of routes
        if 'withdraw' in update:
            if 'ipv4 unicast' in update['withdraw']:
                for route in update['withdraw']['ipv4 unicast']:
                    prefix = route['nlri']
                    if prefix in self.routes:
                        del self.routes[prefix]
                        print(f"[TRACKER] Removed {prefix}, total routes: {len(self.routes)}",
                              file=sys.stderr)

    def get_all_routes(self):
        return self.routes

# Usage
tracker = RouteTracker()
for line in sys.stdin:
    msg = json.loads(line)
    if msg['type'] == 'update':
        tracker.update(msg)

Complete Examples

Example 1: Log All Updates

#!/usr/bin/env python3
"""
log_updates.py - Log all BGP updates to file
"""
import sys
import json
import time

LOG_FILE = '/var/log/exabgp-updates.log'

def log(message):
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
    with open(LOG_FILE, 'a') as f:
        f.write(f"{timestamp} {message}\n")

while True:
    line = sys.stdin.readline()
    if not line:
        break

    try:
        msg = json.loads(line)

        if msg['type'] == 'update':
            update = msg['neighbor']['message']['update']
            peer = msg['neighbor']['address']['peer']

            if 'announce' in update:
                if 'ipv4 unicast' in update['announce']:
                    for routes in update['announce']['ipv4 unicast'].values():
                        for route in routes:
                            if 'nlri' in route:  # an End-of-RIB has none
                                log(f"ANNOUNCE from {peer}: {route['nlri']}")

            if 'withdraw' in update:
                if 'ipv4 unicast' in update['withdraw']:
                    for route in update['withdraw']['ipv4 unicast']:
                        log(f"WITHDRAW from {peer}: {route['nlri']}")

        elif msg['type'] == 'state':
            peer = msg['neighbor']['address']['peer']
            state = msg['neighbor']['state']
            log(f"STATE {peer}: {state}")

    except Exception as e:
        log(f"ERROR: {e}")

Example 2: Trigger Actions on Routes

#!/usr/bin/env python3
"""
route_trigger.py - Trigger actions when specific routes appear
"""
import sys
import json
import subprocess

WATCH_PREFIXES = [
    '100.10.0.0/24',
    '100.20.0.0/24'
]

def trigger_action(prefix, action):
    """Run script when route changes"""
    if action == 'announce':
        subprocess.run(['/etc/exabgp/scripts/on_route_add.sh', prefix])
    elif action == 'withdraw':
        subprocess.run(['/etc/exabgp/scripts/on_route_remove.sh', prefix])

while True:
    line = sys.stdin.readline()
    if not line:
        break

    try:
        msg = json.loads(line)

        if msg['type'] == 'update':
            update = msg['neighbor']['message']['update']

            # Check announcements: next hop -> list of routes
            if 'announce' in update:
                if 'ipv4 unicast' in update['announce']:
                    for routes in update['announce']['ipv4 unicast'].values():
                        for route in routes:
                            prefix = route.get('nlri')  # None for an End-of-RIB
                            if prefix in WATCH_PREFIXES:
                                print(f"[TRIGGER] Route announced: {prefix}", file=sys.stderr)
                                trigger_action(prefix, 'announce')

            # Check withdrawals: list of routes
            if 'withdraw' in update:
                if 'ipv4 unicast' in update['withdraw']:
                    for route in update['withdraw']['ipv4 unicast']:
                        prefix = route['nlri']
                        if prefix in WATCH_PREFIXES:
                            print(f"[TRIGGER] Route withdrawn: {prefix}", file=sys.stderr)
                            trigger_action(prefix, 'withdraw')

    except Exception as e:
        print(f"[ERROR] {e}", file=sys.stderr)

Example 3: Prometheus Metrics Exporter

#!/usr/bin/env python3
"""
metrics.py - Export BGP metrics for Prometheus
"""
import sys
import json
from prometheus_client import start_http_server, Counter, Gauge

# Metrics
routes_announced = Counter('bgp_routes_announced_total', 'Total routes announced')
routes_withdrawn = Counter('bgp_routes_withdrawn_total', 'Total routes withdrawn')
active_routes = Gauge('bgp_active_routes', 'Number of active routes')
session_state = Gauge('bgp_session_up', 'BGP session state (1=up, 0=down)', ['peer'])

# Start metrics server
start_http_server(9101)

route_count = 0

while True:
    line = sys.stdin.readline()
    if not line:
        break

    try:
        msg = json.loads(line)

        if msg['type'] == 'update':
            update = msg['neighbor']['message']['update']

            if 'announce' in update:
                if 'ipv4 unicast' in update['announce']:
                    # next hop -> list of routes; an End-of-RIB has no "nlri"
                    next_hops = update['announce']['ipv4 unicast']
                    count = sum(1 for routes in next_hops.values() for route in routes if 'nlri' in route)
                    routes_announced.inc(count)
                    route_count += count
                    active_routes.set(route_count)

            if 'withdraw' in update:
                if 'ipv4 unicast' in update['withdraw']:
                    count = len(update['withdraw']['ipv4 unicast'])
                    routes_withdrawn.inc(count)
                    route_count -= count
                    active_routes.set(route_count)

        elif msg['type'] == 'state':
            peer = msg['neighbor']['address']['peer']
            state = msg['neighbor']['state']
            session_state.labels(peer=peer).set(1 if state == 'up' else 0)

    except Exception as e:
        print(f"[ERROR] {e}", file=sys.stderr)

Best Practices

1. Always Parse Safely

# Good - safe access
nexthop = attrs.get('next-hop', 'unknown')

# Bad - can raise KeyError
nexthop = attrs['next-hop']

2. Handle Missing Fields

# Address family may not exist
if 'ipv4 unicast' in update.get('announce', {}):
    routes = update['announce']['ipv4 unicast']

3. Process Continuously

# Good - continuous loop
while True:
    line = sys.stdin.readline()
    if not line:
        break
    process(line)

# Bad - read once and exit
line = sys.stdin.readline()
process(line)
# Process exits, ExaBGP restarts it constantly

4. Log to STDERR

# STDOUT is for commands to ExaBGP
# STDERR is for logging
print(f"[INFO] Received route", file=sys.stderr)

5. Catch JSON Errors

try:
    msg = json.loads(line)
except json.JSONDecodeError:
    print(f"[ERROR] Invalid JSON: {line}", file=sys.stderr)
    continue

See Also


Need to send commands? See Text API Reference →


Clone this wiki locally