Skip to content

Instantly share code, notes, and snippets.

@jeffbrl
Last active December 7, 2016 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffbrl/c5819db3e526977fdfdc to your computer and use it in GitHub Desktop.
Save jeffbrl/c5819db3e526977fdfdc to your computer and use it in GitHub Desktop.
Executing Arbitrary Junos 'Show' Commands with PyEZ and ncclient
#!/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