-
-
Save dirkakrid/b5244ac59138f3a40c6099220a9be758 to your computer and use it in GitHub Desktop.
Executing Arbitrary Junos 'Show' Commands with PyEZ and ncclient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Demonstrates the use of the 'command' tag to execute arbritrary 'show' commands. | |
# This code was inspired by Ebben Aries's command-jnpr.py at | |
# https://github.com/leopoul/ncclient/blob/master/examples/juniper/command-jnpr.py | |
# | |
# usage: python ncclient_demo.py <show command> <xpath expression> | |
# python ncclient_demo.py 'show route 2600::/64' '//rt-entry/nh' | |
# | |
# Jeff Loughridge | |
# August 2014 | |
import sys | |
from lxml import etree as etree | |
from ncclient import manager | |
from ncclient.xml_ import * | |
def connect(host, port, user, password, source): | |
try: | |
show_command = sys.argv[1] | |
except IndexError: | |
print "please specify show command as first argument." | |
sys.exit(1) | |
try: | |
xpath_expr = sys.argv[2] | |
except IndexError: | |
xpath_expr='' | |
conn = manager.connect(host=host, | |
port=port, | |
username=user, | |
password=password, | |
timeout=3, | |
device_params = {'name':'junos'}, | |
hostkey_verify=False) | |
try: | |
result = conn.command(command=show_command, format='xml') | |
except Exception, e: | |
print "ncclient_demo.py: Encountered critical error" | |
print e | |
sys.exit(1) | |
tree = etree.XML(result.tostring) | |
if xpath_expr: | |
filtered_tree_list = tree.xpath(xpath_expr) | |
for element in filtered_tree_list: | |
print etree.tostring(element) | |
else: | |
print etree.tostring(tree) | |
if __name__ == '__main__': | |
connect('ROUTER', 830, 'USER', 'PASSWORD', 'candidate') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment