Saving and Loading Junos PyEZ Table XML to and from Files
Junos PyEZ Tables and Views enable you to extract targeted data
from operational command output or the selected configuration database
on a device running Junos OS. You can export Table data as XML, which
enables you to retrieve information for one or more devices and process
it at a later time. Junos PyEZ provides the
savexml() method for this purpose.
savexml() method enables you
to specify a destination file path for the exported data, and optionally
include the device hostname and activity timestamp in the filename.
You can control the format of the timestamp using the standard
For example, suppose that you want to loop through a
list of devices and collect transceiver data using the XcvrTable definition
jnpr.junos.op.xcvr module. The
following code defines a list of device hostnames, prompts the user
for a username and password, and then loops through and makes a connection
to each device:
import sys from getpass import getpass from jnpr.junos import Device from jnpr.junos.op.xcvr import XcvrTable devlist = ['router1.example.com', 'router2.example.com'] user = raw_input('username: ') passwd = getpass('password: ') for host in devlist: sys.stdout.write('connecting to %s ... ' % host) sys.stdout.flush() dev = Device(host,user=user,password=passwd) dev.open() print('ok.') # log data dev.close()
At this point. the program does not yet retrieve any transceiver data. Running the program results in the following output:
user1@server:~$ python xcvr_demo.py
username: user1 password: connecting to router1.example.com ... ok. connecting to router2.example.com ... ok.
To collect and log the transceiver data, you associate
the Table with each target device, retrieve the data, and save it
to a file using the
savexml() method. You
timestamp=True in the
savexml() argument list to append the hostname and timestamp to the output
filename. If you retrieve data for multiple devices in this manner,
you must differentiate the output filename for each device with the
hostname, timestamp, or both to prevent the data for one device from
overwriting the data for the previous device in the same file.
# log data xcvrs = XcvrTable(dev).get() xcvrs.savexml(path='/var/tmp/xcvrs/xcvr.xml', hostname=True, timestamp=True)
path argument assumes that
the target directory exists on your local file system.
After adding the additional code to the device loop in the program and then executing the program, you can examine the contents of the target directory. In this example, the hostname and timestamp values are embedded in the filenames.
user1@server:~$ ls /var/tmp/xcvrs
You can import the XML data at a later time for post processing. To import the data, associate the Table with the XML file instead of a target device. For example:
from jnpr.junos.op.xcvr import XcvrTable xmlpath = '/var/tmp/xcvrs/xcvr_router1.example.com_20131226093921.xml' xcvrs = XcvrTable(path=xmlpath) xcvrs.get()