Try Juniper JUNOS PyEz (python library) Memo 2 ~ Get information with PyEz ~

Last time Now that we have built the environment for PyEz, we will actually try to get JUNOS information this time.

There are several ways to get information using PyEz, but this time I tried these three.

  1. Utilization of facts that can easily obtain basic information that is defined in advance
  2. Utilization of Table and View that can get the contents defined in YAML file
  3. Confirmation equivalent to JUNOS show command by RPC (remote procedure calls)

1. JUNOS information acquisition (facts)

First of all, it is very simple, but as Hello world of PyEz, make a connection from the server to JUNOS and get basic information (hostname, version information, etc.) by facts. facts displays the basic information collected from JUNOS when establishing a NETCONF session. For an overview, see Tech Library There are some, but details can be found on GitHub.

#Import Device module to connect with JUNOS
>>> From juniper. Junos import Device 
#Define device information
>>> dev=Device(host='10.0.0.243', user="xxx", password="xxx", port='22')
#Connect to JUNOS with netconf over ssh
>>> Dev. open ()        
Device(1.1.1.1)
#Basic information display by facts
>>> print dev.facts 
{'domain': None, 'hostname': 'vSRX-1', 'ifd_style': 'CLASSIC', 'version_info': junos.version_info(major=(15, 1), type=X, minor=(49, 'D', 50), build=3), '2RE': False, 'serial number': 'xxxxx', 'fqdn': 'vSRX-1', 'switch_style': 'NONE', 'version': '15.1X49-xxx', 'HOME': '/var/home/vsrx', 'srx_cluster': False, 'model': 'VSRX', 'RE0': {'status': 'Testing', 'last_reboot_reason': '0x10: Misc hardware reason ', 'model': 'VSRX RE', 'up_time': '44 minutes'}, 'vc_capable': False, 'personality': 'UNKNOWN'}
#Only version information is displayed by facts
>>> dev.facts['version']
'15.1X49-xxx'
>>> dev.facts['hostname']
'vSRX-1‘

dev.close()
>>> quit()

Sample to get OS version information using facts and write it to text

from jnpr.junos import Device
from datetime import datetime

mydeviceslist=["1.1.1.1"]
f=open("my_devices_inventory.txt", "a")
f.write(str(datetime.now()) + '\n')
for item in mydeviceslist:
        dev=Device(host=item, user="xxx", password="xxx",port='22')
        dev.open()
        dev.close()
        print ("the device "+ dev.facts["hostname"]+ " is a " + dev.facts['model
'] + " running " + dev.facts["version"])
        f.write ( "the device "+ dev.facts["hostname"]+ " is a " + dev.facts['mo
del'] + " running " + dev.facts["version"] + "\n")
f.close()

Execution result

$ python print_facts.py
the device vSRX-1 is a VSRX running 15.1X49-xxx
[ec2-user@ip-10-0-0-47 facts]$  more my_devices_inventory.txt
2016-08-22 08:01:29.396263 
the device vSRX_AWS-1 is a VSRX running 15.1X49-xxx

2. Get JUNOS information (Table and view)

Each information can be obtained by Table and View defined in YAML using jnpr.junos.op module. The current op module can be found in Documentation Basic information such as arp and interface information can be obtained as it is. As an example, try to get arp information using ArpTable method ..

>>> from jnpr.junos.op.arp import ArpTable
>>> arp1=ArpTable(dev)
>>> arp1.get() 
ArpTable:10.0.0.243: 3 items
#Get a list of keys
>>> arp1.keys()   
['0a:de:e9:03:15:3f', '0a:ca:89:ec:9a:51', '0a:93:06:42:03:c5']
#Get a list of values
>>> arp1.values()   
[[('interface_name', 'fxp0.0'), ('ip_address', '10.0.0.1'), ('mac_address', '0a:de:e9:03:15:3f')], [('interface_name', 'fxp0.0'), ('ip_address', '10.0.0.47'), ('mac_address', '0a:ca:89:ec:9a:51')], [('interface_name', 'ge-0/0/0.0'), ('ip_address', '10.0.1.1'), ('mac_address', '0a:93:06:42:03:c5')]]]

Using RouteTable method, routing information and default gateway table information Sample to display

from jnpr.junos import Device
from jnpr.junos.op.routes import RouteTable

dev = Device(host='10.0.0.243', user='xxx', password='xxx', port='22', gathe
r_facts=False)
dev.open()

tbl = RouteTable(dev)
tbl.get()

#get values and keys
for key, value in tbl.items():
    print "key:%s,\t value:%s" %(key, value)

##print only GW information
print '##this is default gateway'

gw = RouteTable(dev)
gw.get('0.0.0.0')
print gw
for item in gw:
    print 'protocol:', item.protocol
    print 'age:', item.age
    print 'via:', item.via
    print

dev.close()

Execution result

key:0.0.0.0/0,   value:[('nexthop', '10.0.0.1'), ('age', 177947), ('via', 'fxp0.0'), ('protocol', 'Static')]
key:10.0.0.0/24,         value:[('nexthop', None), ('age', 177947), ('via', 'fxp0.0'), ('protocol', 'Direct')]
key:10.0.0.243/32,       value:[('nexthop', None), ('age', 181163), ('via', 'fxp0.0'), ('protocol', 'Local')]
key:10.0.1.0/24,         value:[('nexthop', None), ('age', 181145), ('via', 'ge-0/0/0.0'), ('protocol', 'Direct')]
key:10.0.1.68/32,        value:[('nexthop', None), ('age', 181146), ('via', 'ge-0/0/0.0'), ('protocol', 'Local')]
key:10.0.2.98/32,        value:[('nexthop', None), ('age', 181144), ('via', 'ge-0/0/1.0'), ('protocol', 'Direct')]
key:10.0.3.85/32,        value:[('nexthop', None), ('age', 181144), ('via', 'ge-0/0/2.0'), ('protocol', 'Direct')]
key:192.168.0.1/32,      value:[('nexthop', None), ('age', 181162), ('via', 'lo0.0'), ('protocol', 'Direct')]
##this is default gateway
RouteTable:10.0.0.243: 1 items
protocol: Static
age: 177947
via: fxp0.0

You can also define your own YAML file to get the Table and View. As a sample that fell into Git, for example, this.

3. Get JUNOS information (RPC, show command)

Finally, with the CLI show command using RPC Try to get the equivalent information.

-Show command and RPC mapping

The JUNOS XML API is an XML representation of JUNOS config and operation mode commands. You can get an XML response by making a request with RPC. In PyEz, RPC will be executed, but since CLI commands and RPC can be mapped, the CLI you want to use will be used as RPC.

To do this, you need to check which CLI is which RPC, but here are two ways to do it.

  1. Check with the show command on the actual JUNOS machine Check with | display xml rpc after the show command you want to use. For example, in the case of show interface
> show interfaces  | display xml rpc
<rpc-reply xmlns:junos="http://xml.juniper.net/junos/15.1X49/junos">
    <rpc>
        <get-interface-information>
        </get-interface-information>
    </rpc>
    <cli>
        <banner></banner>
    </cli>
</rpc-reply>
  1. Check with PyEz's display_xml_rpc () method After connecting to JUNOS with dev.open (), specify the show command you want to use in the dev.display_xml_rpc method and check.
>>> print dev.display_xml_rpc('show interface', format='text')
<get-interface-information>
</get-interface-information>
>>>

From these checks, you can see that the show interface is a tag \ </ get-route-information>. Next, we need to convert the tag to RPC, but change the hyphen (-) to an underscore (_) and eliminate the angle brackets. That is, in the case of \ , the RPC becomes get_interface_information (). All you have to do is use this RPC method. If you do not specify the option, it will be returned in XML, so lxml.etree library will also be imported, formatted and displayed. Use etree.tostring () to do this.

-Sample to check show interface

from jnpr.junos import Device
from lxml import etree

  dev = Device(xxxx,xxx,xxx,xx)
  dev.open()

int=dev.rpc.get_interface_information()
print(etree.tostring(int))

-Use show command option (no value) If the show command option does not use a value, you can check it by setting = True in the RPC method parameter.

For example, a sample to check show interface terse

dev.open()
int=dev.rpc.get_interface_information(terse=True)
print(etree.tostring(int))

-Use show command option (with value) When using a value as an option of the show command, convert the XML of the option to the RPC method in the same way, and specify the option with equal.

For example, if you specify the interface of show interface, you can see that the tag is \ .

> show interfaces ge-0/0/0 | display xml rpc
<rpc-reply xmlns:junos="http://xml.juniper.net/junos/15.1X49/junos">
    <rpc>
        <get-interface-information>
                <interface-name>ge-0/0/0</interface-name>
        </get-interface-information>
    </rpc>
    <cli>

Therefore, as RPC, it becomes interface_name, so specify as follows.

>>> int=dev.rpc.get_interface_information(interface_name='ge-0/0/0')
>>> print(etree.tostring(int))

You can also normalize the returned XML with dev.rpc.rpc_method (normalize = True). It also seems possible to display the reply in a non-XML way.

4. Summary

I wrote it like a memo, but For the time being, I tried to get information in several ways using PyEz. Next time I will try changing the settings.

5. Reference link

PyEz Sample Scripts (on Git by Nitin Kumar)

Recommended Posts

Try Juniper JUNOS PyEz (python library) Memo 2 ~ Get information with PyEz ~
Try Juniper JUNOS PyEz (python library) Memo 3 ~ Change settings with PyEz ~
Try Juniper JUNOS PyEz (python library) Memo 1 ~ PyEz Overview ~
Get Alembic information with Python
Get weather information with Python & scraping
Get property information by scraping with python
Try HTML scraping with a Python library
[Python] Get Python package information with PyPI API
[Personal memo] julia --Using Python library with julia using PyCall
Get CPU information of Raspberry Pi with Python
Python script to get note information with REAPER
Location information data display in Python --Try plotting with the map display library (folium)-
Try scraping with Python.
Get date with python
[First API] Try to get Qiita articles with Python
[Python] Get user information and article information with Qiita API
Get country code with python
Try to display various information useful for debugging with python
Twitter graphing memo with Python
Get Twitter timeline with python
Try Python output with Haxe 3.2
Get Youtube data with python
Get information with zabbix api
Get thread ID with python
Try running Python with Try Jupyter
Get started with Python! ~ ② Grammar ~
Try face recognition with Python
Get stock price with Python
[Python x Zapier] Get alert information and notify with Slack
Try to display google map and geospatial information authority map with python
Try to get CloudWatch metrics with re: dash python data source
PhytoMine-I tried to get the genetic information of plants with Python
Try scraping with Python + Beautiful Soup
Get video file information with ffmpeg-python
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Get reviews with python googlemap api
Try to operate Facebook with Python
python memo --Specify options with getopt
Try singular value decomposition with Python
Input / output with Python (Python learning memo ⑤)
Get the weather with Python requests
Get web screen capture with python
Get the weather with Python requests 2
[Python] Get economic data with DataReader
How to get started with Python
[python] Read information with Redmine API
[Small story] Get timestamp with Python
Get, post communication memo in Python
Get Qiita trends with Python scraping
[Hyperledger Iroha] Query with Python library
Try frequency control simulation with Python
"Scraping & machine learning with Python" Learning memo
Get started with Python in Blender
[Memo] Tweet on twitter with python
[Yahoo! Weather Replacement Version] How to get weather information with LINE Notify + Python
Try using APSW, a Python library that SQLite can get serious about
I tried to get the movie information of TMDb API with Python
Collecting information from Twitter with Python (Twitter API)
Get additional data in LDAP with python
Try to reproduce color film with Python