PyangBind

0.8.7 · active · verified Thu Apr 16

PyangBind is a plugin for `pyang` that converts YANG data models into a Python class hierarchy, enabling Python to manipulate data conforming to a YANG model. It facilitates programmatic interaction with network device configurations and operational state. The current version is 0.8.7, and releases are typically made a few times per year, often driven by bug fixes or new feature support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple YANG model, generate Python bindings using the `pyang` tool with the `pybind` plugin, and then interact with the generated Python classes to set data and serialize it to a dictionary.

import os

# 1. Create a simple YANG model file (e.g., 'example.yang')
yang_model_content = '''
module example {
  yang-version 1;
  namespace "urn:example:pyangbind:test";
  prefix "ex";

  container config {
    leaf hostname {
      type string;
      description "Device hostname.";
    }
    leaf-list interfaces {
      type string;
      description "List of interfaces.";
    }
  }
}
'''
with open('example.yang', 'w') as f:
    f.write(yang_model_content)

# 2. Generate Python bindings using pyang
# This command is typically run from the command line, not Python.
# For demonstration, we simulate it.
# In a real scenario, you'd run: pyang -f pybind -o my_bindings.py example.yang
import subprocess
try:
    subprocess.run(['pyang', '-f', 'pybind', '-o', 'my_bindings.py', 'example.yang'], check=True)
    print("Bindings generated successfully to my_bindings.py")
except FileNotFoundError:
    print("Error: 'pyang' command not found. Ensure pyangbind is installed correctly.")
    exit(1)
except subprocess.CalledProcessError as e:
    print(f"Error generating bindings: {e}")
    print(e.stderr.decode())
    exit(1)

# 3. Use the generated Python classes
import my_bindings
from pyangbind.lib.serialise import pybind_to_dict

# Instantiate the top-level module class
# The class name is typically derived from the YANG module name (e.g., 'example')
inst = my_bindings.example()

# Set values for the 'config' container and its leaves
inst.config.hostname = "my-device-1"
inst.config.interfaces.add("eth0")
inst.config.interfaces.add("eth1")

# Access and print values
print(f"Hostname: {inst.config.hostname}")
print(f"Interfaces: {list(inst.config.interfaces)}")

# Serialize the object to a dictionary
data_dict = pybind_to_dict(inst)
print("\nSerialized data:")
import json
print(json.dumps(data_dict, indent=2))

# Clean up generated files
os.remove('example.yang')
os.remove('my_bindings.py')

view raw JSON →