Monday, January 5, 2015

Controlling Junos with Python & PyEZ, Part 2: Getting Info, RPC on Demand

At first part of this post, i've tried to explain how to install PyEZ module on Windows, and how to get the device name. Surely the power of python, PyEZ framework and XML API of Junos is not limited with that, so let's get into detail.

RPC on Demand

For any command you can execute on Junos CLI, you can invoke it's RPC equivalent. To determine an RPC equivalent of a command, you use the | display xml rpc mechanism as illustrated:

etorun@as34984-lg> show route | display xml rpc 
<rpc-reply xmlns:junos="">

The content between the "<rpc>...</rpc>" is the XML RPC command, in this case "get_route_information". Be careful you need to swap dashes (-) to underscores(_) 

show_route_output = testdevice.rpc.get_route_information(destination="")

If you wanted search active route for in inet.0 table, then you need to add parameters to the same command, but the command you need to execute to get the rpc equivalent does not change.
etorun@as34984-lg> show route table inet.0 active-path | display xml rpc 
<rpc-reply xmlns:junos="">

However you need to add these extra parameters to python equivalent

show_route_output = testdevice.rpc.get_route_information(destination="", table="inet.0", active_path=True) 

The "active-path" parameter does not take any value, so just assign it to True

To determine the  RPC response use the | display xml mechanism

etorun@as34984-lg> show route table inet.0 active-path | display xml        
<rpc-reply xmlns:junos="">
    <route-information xmlns="">
            <rt junos:style="brief">
                    <age junos:seconds="791658">1w2d 03:54:18</age>
                    <as-path>15169 I

Trying It Out

Imagine you need to take the active as-path value of Then the python script should be:

from jnpr.junos import Device
from jnpr.junos import Device
router = Device(user='admin', host='', password='logmein')
# invoke the RPC equivalent to "show route table inet.0 active-path"
show_route_output = router.rpc.get_route_information(destination="", table="inet.0", active_path=True) 
# use XPath expressions to extract the data from the Junos/XML response# the :show_route_output: variable is an lxml Element object
print "the as-path value is: %s" % show_route_output.findtext('route-table/rt/rt-entry/as-path')

Here is the output when i run the .py file from windows powershell:

If you wanted to have a look, I did benefit from RPC On Demand page of Juniper Tech Wiki when writing this post.


Post a Comment


Internetworking Hints Copyright © 2011 -- Template created by O Pregador -- Powered by Blogger