PyangBind<\/a> is a plugin for Pyang that generates a Python class hierarchy from a YANG data model. Interaction to resulting classes can then be performed within Python.<\/p>\nFirst, let us define the path of PyangBind as an environment variable.<\/p>\n
$ export PYBINDPLUGIN=`\/usr\/bin\/env python -c \\\r\n\t'import pyangbind; import os; print \"%s\/plugin\" % os.path.dirname(pyangbind.__file__)'`\r\n$ echo $PYBINDPLUGIN<\/pre>\nWe then run Pyang, using the Pyangbind module. Within the command we set the file type, the output filename and the YANG models we are ingesting.<\/p>\n
$ pyang --plugindir $PYBINDPLUGIN -f pybind -o ietf_ip_binding.py ietf-ip.yang ietf-interfaces.yang ietf-inet-types.yang<\/pre>\n<\/span>Model Changes<\/span><\/h3>\nNow that we have our Python binding, we can import this and work upon the model using the standard Python features.<\/p>\n
First we import the binding,<\/p>\n
from ietf_ip_binding import ietf_interfaces\r\nfrom pprint import pprint\r\n\r\nmodel = ietf_interfaces()\r\nmodel.get()\r\n\r\n...\r\n\r\n{'interfaces-state': {'interface': OrderedDict()}, 'interfaces': {'interface': OrderedDict()}}\r\n<\/pre>\nLets add an interface to the model,<\/p>\n
interface_ge3 = model.interfaces.interface.add('GigabitEthernet3')\r\npprint(interface_ge3.get())\r\n\r\n...\r\n\r\n{'description': u'',\r\n 'enabled': True,\r\n 'ipv4': {'address': OrderedDict(),\r\n 'enabled': True,\r\n 'forwarding': False,\r\n 'mtu': 0,\r\n 'neighbor': OrderedDict()},\r\n 'ipv6': {'address': OrderedDict(),\r\n 'autoconf': {'create-global-addresses': True,\r\n 'create-temporary-addresses': False,\r\n 'temporary-preferred-lifetime': 86400L,\r\n 'temporary-valid-lifetime': 604800L},\r\n 'dup-addr-detect-transmits': 1L,\r\n 'enabled': True,\r\n 'forwarding': False,\r\n 'mtu': 0L,\r\n 'neighbor': OrderedDict()},\r\n 'link-up-down-trap-enable': u'',\r\n 'name': u'GigabitEthernet3',\r\n 'type': u''}<\/pre>\nGreat. Lets make some changes to the interface (add ip\/mask and admin down),<\/p>\n
interface_ge3.enabled = False\r\ninterface_ge3_addr = interface_ge3.ipv4.address.add('2.2.2.2')\r\ninterface_ge3_addr.netmask = '255.255.0.0'\r\n\r\npprint(interface_ge3.get())\r\n\r\n...\r\n\r\n{'description': u'',\r\n 'enabled': False,\r\n 'ipv4': {'address': OrderedDict([('2.2.2.2', {'ip': u'2.2.2.2', 'netmask': u'255.255.0.0', 'prefix-length': 0})]),\r\n 'enabled': False,\r\n 'forwarding': False,\r\n 'mtu': 1460,<\/pre>\nThis model is then saved back into a file. Please note : Pyang currently only supports JSON as a data type for export.<\/p>\n
import pyangbind.lib.pybindJSON as pybindJSON\r\nfrom file import read_file, write_file\r\n\r\njson_data = pybindJSON.dumps(model, mode='ietf')\r\nwrite_file(json_data, \"interface_ge3.json\")<\/pre>\n