Automation
Automation

How-To: Save table data

by on ‎08-06-2015 04:44 AM - edited on ‎09-15-2017 04:19 PM by Administrator Administrator (4,509 Views)

Overview

You want to save Table data for a number of devices so you can post-process the information at a later time.

 

Solution

 

The Table widget includes a savexml() method for this purpose.  The savexml() method allows you to specify a destination file path, and optionally include the device hostname and activity timestamp with the name.  You can also control the format of the timestamp using standard strftime format.

 

Discussion

 

Let's say that you've got a list of devices that you want to loop through and collect Transceiver data (Xcvr). 

 

Your program starts out looking like the following "skeleton-code".  You have a list of device hostnames, and you prompt the user for their username and password.  You then loop through the hostnames, making a connection to the remote device.  We call this "skeleton-code" since it really doesn't do anything, it's just a skeleton for adding our functionality into the main loop, as you will see.

 

01 import sys
02 from getpass import getpass
03 from jnpr.junos import Device
04 from jnpr.junos.op.xcvr import XcvrTable
05  
06 devlist = ['mx240.chi','mx480.chi','mx80.chi','srx3400.chi']
07 user = raw_input('username: ')
08 passwd = getpass('password: ')
09  
10 for host in devlist:
11   sys.stdout.write('connecting to %s ... ' % host)
12   sys.stdout.flush()
13    
14   dev = Device(host,user=user,password=passwd)
15   dev.open()
16   print('ok.')
17  
18   # log_xcvr_data( dev )
19  
20   dev.close()

 

Running this program at this point results in the output:

 

1 [jeremy@linux]$ python xcvr_demo.py
2 username: jschulman
3 password:
4 connecting to mx240.chi ... ok.
5 connecting to mx480.chi ... ok.
6 connecting to mx80.chi ... ok.
7 connecting to srx3400.chi ... ok.

 

Now let's add the collecting and logging of Xcvr data to the skeleton.  We'll create a function called log_xcvr_data() and pass that function the device, like this:

 

1 def log_xcvr_data(dev):
2   xcvrs = XcvrTable(dev)
3   xcvrs.get()
4   xcvrs.savexml(path='/var/tmp/xcvrs/xcvr.xml', hostname=True, timestamp=True)
Note: The above assumes that the directory "/var/tmp/xcvrs" exists on your local file system. 

Once this program executes, we can examine the contents of that directory:

 

1 [jeremy@linux]$ ls /var/tmp/xcvrs
2 xcvrs_CHI-MX480-re0_20131226093921.xml   xcvrs_CHI-SRX3400-1_20131226093939.xml
3 xcvrs_CHI-MX80-48T-1_20131226093930.xml  xcvrs_NYCD-MX240-1_20131226093913.xml

 

Here you can see that the <hostname> and <timestamp> values have been embedded into each filename.

 

You can later import these XML data files back into a Table widget for post processing.  That process is described in a "How-To" found here.

Feedback