PyEZ examples

In the previous interactive prompt, we already saw that when the device connects, the object already automatically retrieves a few facts about the device. In our first example, junos_pyez_1.py, we are connecting to the device and executing a RPC call for show interface em1:

      #!/usr/bin/env python3
from jnpr.junos import Device
import xml.etree.ElementTree as ET
import pprint

dev = Device(host='192.168.24.252', user='juniper', passwd='juniper!')

try:
dev.open()
except Exception as err:
print(err)
sys.exit(1)

result =
dev.rpc.get_interface_information(interface_name='em1', terse=True)
pprint.pprint(ET.tostring(result))

dev.close()

The device class has a proper of the rpc property that includes all operational commands. This is pretty awesome because there is no slippage between what we can do in CLI vs. API. The catch is that we need to find out the xml rpc element tag. In our first example, how do we know show interface em1 equates to get_interface_information? We have three ways of finding out about the information:

  1. We can reference the Junos XML API Operational Developer Reference.
  2. We can also use the CLI and display the XML RPC equivalent and replace the dash (-) between the words with underscore (_).
  3. We can also do this programmatically using the PyEZ library.

I typically use the second option to get the output directly:

    netconf@foo> show interfaces em1 | display xml rpc
<rpc-reply xmlns:junos="http://xml.juniper.net/junos/12.1R1/junos">
<rpc>
<get-interface-information>
<interface-name>em1</interface-name>
</get-interface-information>
</rpc>
<cli>
<banner></banner>
</cli>
</rpc-reply>

However, a third option is also feasible:

    >>> dev1.display_xml_rpc('show interfaces em1', format='text')
'<get-interface-information>n <interface-name>em1</interface-
name>n</get-interface-information>n'

Of course, we will need to make configuration changes as well. In the junos_pyez_2.py configuration example, we will import an additional Config() method from PyEZ:

      #!/usr/bin/env python3
from jnpr.junos import Device
from jnpr.junos.utils.config import Config

We will utilize the same block for connecting to a device:

      dev = Device(host='192.168.24.252', user='juniper', 
passwd='juniper!')

try:
dev.open()
except Exception as err:
print(err)
sys.exit(1)

The new Config() method will load the XML data and make the configuration changes:

      config_change = """
<system>
<host-name>master</host-name>
<domain-name>python</domain-name>
</system>
"""

cu = Config(dev)
cu.lock()
cu.load(config_change)
cu.commit()
cu.unlock()

dev.close()

The PyEZ examples are simple by design, but hopefully, they demonstrate the ways you can leverage PyEZ for your Junos automation needs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.67.16