├── Dockerfile ├── LICENSE ├── NOTICE ├── README.md ├── application └── cableplan │ ├── .coverage │ ├── cableplan.py │ ├── docs │ └── cable.rst │ └── nexusCableplan_test.py ├── contributors.txt ├── docs └── Makefile ├── nxtoolkit ├── __about__.py ├── __init__.py ├── nxConcreteLib.py ├── nxSearch.py ├── nxTable.py ├── nxbaseobject.py ├── nxcounters.py ├── nxfakeswitch.py ├── nxphysobject.py ├── nxsession.py ├── nxtoolkit.py └── nxtoolkitlib.py ├── pylintrc ├── samples ├── README.md ├── nx-config-arp.py ├── nx-config-bootNxos.py ├── nx-config-dhcp.py ├── nx-config-dns.py ├── nx-config-feature.py ├── nx-config-icmp.py ├── nx-config-ifmgr.py ├── nx-config-interface.py ├── nx-config-ipv4.py ├── nx-config-ipv6.py ├── nx-config-lacp.py ├── nx-config-nd.py ├── nx-config-port-channel.py ├── nx-config-rbac.py ├── nx-config-rpm.py ├── nx-config-stp.py ├── nx-config-svi.py ├── nx-config-syslog.py ├── nx-config-udld.py ├── nx-config-vlan.py ├── nx-config-vrrp.py ├── nx-copy-running-startup.py ├── nx-create-bgp.py ├── nx-create-l2bds.py ├── nx-show-bgp.py ├── nx-show-cdp-neighbors.py ├── nx-show-dns.py ├── nx-show-fantrays.py ├── nx-show-hardware-buffer.py ├── nx-show-ifs.py ├── nx-show-interface-stats.py ├── nx-show-interfaces.py ├── nx-show-ip.py ├── nx-show-l2bds.py ├── nx-show-linecards.py ├── nx-show-port-channel.py ├── nx-show-process.py ├── nx-show-psus.py ├── nx-show-rbac.py ├── nx-show-rpm.py ├── nx-show-supervisors.py ├── nx-show-syslog.py └── nx-show-vrrp.py ├── scripts └── install_dependencies ├── setup.py ├── shippable.yml └── tests ├── README.md ├── nxTable_test.py ├── nxtoolkit_test.py └── nxtoolkitlib_test.py /Dockerfile: -------------------------------------------------------------------------------- 1 | # VERSION 1.0 2 | FROM ubuntu 3 | MAINTAINER Ranga Rao, rangrao@cisco.com 4 | RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list 5 | RUN apt-get update 6 | RUN apt-get -y install git python python-pip 7 | WORKDIR /opt 8 | RUN git clone https://github.com/datacenter/nxtoolkit 9 | WORKDIR nxtoolkit 10 | RUN python setup.py install 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2015 Cisco Systems, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | nxtoolkit uses the requests library. 2 | http://docs.python-requests.org/en/latest/ 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nxtoolkit [![Documentation Status](https://readthedocs.org/projects/nxtoolkit/badge/?version=latest)](https://readthedocs.org/projects/nxtoolkit/?badge=latest) [![Build Status](https://api.shippable.com/projects/54ea96315ab6cc13528d52ad/badge?branchName=master)](https://app.shippable.com/projects/54ea96315ab6cc13528d52ad/builds/latest) [![Code Health](https://landscape.io/github/datacenter/nxtoolkit/master/landscape.svg?style=flat)](https://landscape.io/github/datacenter/nxtoolkit/master) 2 | 3 | 4 | # Description 5 | Command line interface is being used so far extensively to control and manage network switches. But the CLI dependance could be holding us back, preventing from true programmability in those switches and more comprehensive automation of our network. 6 | 7 | Object Model/NX-API REST used in ACI and of the Cisco NX-OS provide an advanced framework for network control and achieve true network programmability 8 | NXtoolkit is a object based programmability in the Open NX-OS.Nxtoolkit is a set of python libraries that allow basic configuration of the Cisco Nexus 9000/3000 Series Switch. It is intended to allow users to quickly begin using the REST API and accelerate the process of programming and automating a Cisco Nexus 9000/3000 based network. 9 | 10 | The NX Toolkit is a set of python libraries that allow basic configuration of the Cisco Nexus Switch. It is intended to allow users to quickly begin using the REST API and accelerate the learning curve necessary to begin using the Switch. 11 | 12 | 13 | # Installation 14 | 15 | ## Environment 16 | 17 | Required 18 | 19 | * Python 2.7+ 20 | * [setuptools package](https://pypi.python.org/pypi/setuptools) 21 | * NXOS version: 7.0(3)I2(1) 22 | 23 | ## Downloading 24 | 25 | Option A: 26 | 27 | If you have git installed, clone the repository 28 | 29 | git clone https://github.com/datacenter/nxtoolkit.git 30 | 31 | Option B: 32 | 33 | If you don't have git, [download a zip copy of the repository](https://github.com/datacenter/nxtoolkit/archive/master.zip) and extract. 34 | 35 | Option C: 36 | 37 | The latest build of this project is also available as a Docker image from Docker Hub 38 | 39 | docker pull dockercisco/nxtoolkit 40 | 41 | ## Installing 42 | 43 | After downloading, install using setuptools. 44 | 45 | cd nxtoolkit 46 | python setup.py install 47 | 48 | If you plan on modifying the actual toolkit files, you should install the developer environment that will link the package installation to your development directory. 49 | 50 | cd nxtoolkit 51 | python setup.py develop 52 | 53 | # Usage 54 | 55 | A tutorial and overview of the nxtoolkit object model can be found in 56 | the Documentation section found at 57 | [http://datacenter.github.io/nxtoolkit/](http://datacenter.github.io/nxtoolkit/) 58 | 59 | # License 60 | 61 | Copyright 2015 Cisco Systems, Inc. 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /application/cableplan/.coverage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/datacenter/nxtoolkit/f03872793a31613c3b7498a8d65cfac3080aeee0/application/cableplan/.coverage -------------------------------------------------------------------------------- /application/cableplan/docs/cable.rst: -------------------------------------------------------------------------------- 1 | cableplan module 2 | ==================== 3 | The Cable Plan module allows the programmer to easily import existing 4 | cable plans from XML files, import the currently running cable plan 5 | from a switch, export previously imported cable plans to a 6 | file, and compare cable plans. 7 | 8 | More advanced users can use the Cable Plan to easily build a cable plan XML 9 | file, query a cable plan, and modify a cable plan. 10 | 11 | 12 | .. _tut-using: 13 | 14 | **************************** 15 | Using the Cable Plan module 16 | **************************** 17 | 18 | 19 | .. _tut-invoking: 20 | 21 | Invoking 22 | ======================== 23 | 24 | The Cable Plan module is imported from the :file:`cable.py`.:: 25 | 26 | from cable import CABLEPLAN 27 | 28 | When you want to create a cable plan from the current running Switch 29 | simply do the following:: 30 | 31 | cp = CABLEPLAN.get(session) 32 | 33 | Where ``session`` is a Switch session object generated using the 34 | ``acitoolkit``. ``cp`` will be the cable plan object. 35 | 36 | You can export that cable plan by opening a file and calling the 37 | ``export()`` method as follows:: 38 | 39 | cpFile = open('cableplan1.xml','w') 40 | cp.export(cpFile) 41 | cpFile.close() 42 | 43 | The cable plan will be written to the :file:`cableplan1.xml`. 44 | 45 | Reading an existing cable plan xml file is equally easy.:: 46 | 47 | fileName = 'cableplan2.xml' 48 | cp2 = CABLEPLAN.get(fileName) 49 | 50 | Note that you don't have to explicitly open or close the file. The 51 | ``get(fileName)`` method will take care of that for you. 52 | 53 | Comparing cable plans is one of the more interesting cabablilities of 54 | the Cable Plan module and is very easy to do using the "difference" 55 | methods. When generating the difference between two cable plans, the 56 | module will return those items that exist in the first cable plan, but 57 | not in the second. 58 | 59 | For example, assume that in the above example, the second cable plan 60 | read from the :file:`cableplan2.xml` does not have switch "Spine3" 61 | and the first cable plan does have it. The following example will 62 | print all of the switches in the first cable plan and not in the 63 | second.:: 64 | 65 | missing_switches = cp1.difference_switch(cp2) 66 | for switch in missing_switches : 67 | print switch.get_name() 68 | 69 | This will print the following:: 70 | 71 | Spine3 72 | 73 | Similiarly, the following example will print all of the missing 74 | links:: 75 | 76 | missing_links = cp1.difference_link(cp2) 77 | for link in missing_links : 78 | print link.get_name() 79 | 80 | To understand all of the differences between two cable plans it is 81 | necessary to compare them in both directions :: 82 | 83 | missing_links = cp1.difference_link(cp2) 84 | extra_links = cp2.difference_link(cp1) 85 | print 'The following links are missing from the second cable plan' 86 | for link in missing_links : 87 | print link.get_name() 88 | print 'The following links are extra links in the second cable plan' 89 | for link in extra_links: 90 | print link.get_name() 91 | 92 | If multiple ports are specified in the link object with minPorts and 93 | maxPorts attributes (see Cable Plan XML Syntax below), it is possible 94 | that a link object in the first cable plan is only partially met by 95 | the link objects in the second cable plan. The ``remaining_need()`` 96 | method of the CpLink object.:: 97 | 98 | missing_links = cp1.difference_link(cp2) 99 | for link in missing_links : 100 | print 'Link',link.get_name(), 'still 101 | needs',link.remaining_need(),'links to satisfy its mimimum 102 | requirement' 103 | 104 | There is a similar method, ``remaining_avail()`` that returns the 105 | number of physical links the link object could match. 106 | 107 | The ``remaining_need()`` and ``remaining_avail()`` values are reset when 108 | the ``difference_link()`` method is invoked. 109 | 110 | It might be necessary to compare cable plans when the names of the 111 | switches are different, but the topologies are the same. This can 112 | easily done by simply changing the names of the switches that are 113 | different and then doing the comparisons.:: 114 | 115 | switch = cp1.get_switch('Spine1') 116 | switch.set_name('Spine1_new_name') 117 | 118 | This will automatically also fix-up all of the link names that are 119 | connected to the switch whose name is being changed. Note that this 120 | is also an easy way to change the name of a switch in a cable plan 121 | file. Simply read it in, change the switch name, and export it out. 122 | The following example will read in :file:`cable_plan2.xml`, change the 123 | name of 'Leaf1' to 'Leaf35', and then export to the same file the 124 | modified cable plan:: 125 | 126 | fileName = 'cable_plan2.xml' 127 | cp2 = CABLEPLAN.get(fileName) 128 | switch = cp2.get_switch('Leaf1') 129 | switch.set_name('Leaf35') 130 | f = open(fileName,'w') 131 | cp2.export(f) 132 | f.close() 133 | 134 | Cable Plan XML Syntax 135 | ======================== 136 | The cable plan XML looks like the following :: 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | The CHASSIS_INFO tag normally identifies the spine switches and the 156 | leaf switches are contained in the LINK_INFO. When the XML is read 157 | in, both leaf and spine switch objects will be created and the 158 | ``get_switch()`` and ``get_link()`` methods can be used to access 159 | them. 160 | 161 | The LINK_INFO syntax also allows more flexible and loose 162 | specifications of the links. If the ``sourcePort`` or ``destPort`` 163 | attributes are left out, then any port on that corresponding switch 164 | can be used. The ``sourcePort`` and ``destPort`` attributes can also 165 | take port ranges, and lists as shown here:: 166 | 167 | 169 | 170 | In addition, you can add ``minPorts`` and ``maxPorts`` attributes to 171 | specify the minimum number of ports or maximum number of ports when 172 | multiple are defined.:: 173 | 174 | 177 | 178 | If minPorts is omitted, the default will be 1. If maxPorts is 179 | omitted, the default will be unlimited. 180 | 181 | When comparing two cable plans using the ``difference_link()`` method, 182 | if the minimum number of links in the first cable plan can be met with 183 | second cable plan, then the difference will show no difference. Note 184 | that it is possible that requirements of several links specified in 185 | one cable plan may be met by one or more links in the other. 186 | Basically, the difference is calculated such that the minimum 187 | requirements of the first cable plan are met without exceeding the 188 | maximum capacity of the second cable plan. 189 | 190 | 191 | .. automodule:: cable 192 | :members: 193 | :undoc-members: 194 | :show-inheritance: 195 | -------------------------------------------------------------------------------- /contributors.txt: -------------------------------------------------------------------------------- 1 | Ranga Rao rangrao@cisco.com 2 | Michael Smith michsmit@cisco.com 3 | Bon Huang bonhuan@cisco.com 4 | Tom Edsall edsall@cisco.com 5 | Kevin Corbin kecorbin@cisco.com 6 | Titu Nahak tnahak@cisco.com 7 | Nishmitha Sudakar nsudakar@cisco.com 8 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = ../docsbuild 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nxtoolkit.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nxtoolkit.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/nxtoolkit" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nxtoolkit" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /nxtoolkit/__about__.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | __all__ = [ 14 | "__title__", "__summary__", "__uri__", "__version__", "__author__", 15 | "__email__", "__license__", "__copyright__", 16 | ] 17 | 18 | __title__ = "nxtoolkit" 19 | __summary__ = "Toolkit for Cisco Nexus Switches" 20 | __uri__ = "http://datacenter.github.io/nxtoolkit/" 21 | 22 | __version__ = "0.2" 23 | 24 | __author__ = "Cisco Systems, Inc." 25 | __email__ = "nxtoolkit@external.cisco.com" 26 | 27 | __license__ = "Apache License, Version 2.0" 28 | __copyright__ = "2015 %s" % __author__ 29 | -------------------------------------------------------------------------------- /nxtoolkit/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from .__about__ import ( 14 | __author__, __copyright__, __email__, __license__, __summary__, __title__, 15 | __uri__, __version__, 16 | ) 17 | 18 | 19 | __all__ = [ 20 | "__author__", "__copyright__", "__email__", "__license__", "__summary__", 21 | "__title__", "__uri__", "__version__", 22 | ] 23 | 24 | -------------------------------------------------------------------------------- /nxtoolkit/nxSearch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | # all the import 21 | 22 | 23 | class Searchable(object): 24 | """ 25 | This class hold a search term as a keyword, value pair and a list 26 | of nxtoolkit objects that are related to that term. The first 27 | item on the list is the object where the term came from and is considered a "primary" object. Subsequent objects 28 | on the list are added as the instance of Searchable is passed up the object heirarchy and 29 | they provide context for the primary object. 30 | 31 | For example, a search term might be an ip address. The list might then objects representing, in order. 32 | 33 | The relationship of the search term to the primary nxtoolkit object can either be `direct` or `indirect`. 34 | A `direct` relationship is one where the object is a primary source or the source closest to where the search term 35 | comes from. An `indirect` relationship is one where the object has learned the information from some other place 36 | or has be informed of the information from another place. 37 | 38 | An example might be the ip address of a tunnel end-point. If switch A learns the address of switch B, then switch 39 | A has an `indirect` relation to the address while switch B would have a `direct` relation to that address. 40 | 41 | This `direct`/`indirect` relationship can be used by an application that is displaying the information to 42 | prioritize which ones are displayed first, i.e. to rank them. 43 | """ 44 | def __init__(self, keyword, value=None, relation='primary'): 45 | """ 46 | Creates report of basic switch information 47 | :param keyword: Keyword for a search 48 | :param value: Optional value for the keyword 49 | :param relation: Indication of whether the information is first hand, 50 | primary, or indirect 51 | """ 52 | if isinstance(value, unicode): 53 | value = str(value) 54 | if isinstance(keyword, unicode): 55 | keyword = str(keyword) 56 | 57 | assert relation in ['primary', 'indirect'] 58 | assert isinstance(value, str) or (value is None) 59 | 60 | self.value = value 61 | 62 | assert isinstance(keyword, str) 63 | self.keyword = keyword 64 | self.relation = relation 65 | self.context = [] 66 | 67 | def add_context(self, nx_object): 68 | """ 69 | Method to add an nxobject to a Searchable instance. It will simply be 70 | appended to the end of the list 71 | 72 | :param nx_object: nxtoolkit object 73 | """ 74 | self.context.append(nx_object) 75 | 76 | def __str__(self): 77 | if len(self.context) > 0: 78 | primary_object = type(self.context[0]) 79 | else: 80 | primary_object = 'None' 81 | return '{0:>18}::{1:<18} {2}'.format(self.keyword, self.value, primary_object) 82 | 83 | def __eq__(self, other): 84 | """ 85 | Two searchables are equal if all the attributes are equal 86 | """ 87 | if self.value != other.value: 88 | return False 89 | 90 | if self.keyword != other.keyword: 91 | return False 92 | 93 | if self.relation != other.relation: 94 | return False 95 | 96 | if len(self.context) != len(other.context): 97 | return False 98 | 99 | for index in range(len(self.context)): 100 | if self.context[index] != other.context[index]: 101 | return False 102 | 103 | return True 104 | 105 | 106 | 107 | class NxSearch(object): 108 | """ 109 | This class is a base class that creates a method for rolling up through 110 | the object heirarchy all of the Searchable instances. 111 | """ 112 | 113 | def get_searchable(self): 114 | """ 115 | Method to recursively retrieve all of the searchable items from all 116 | the children objects, add the current object to them as additional 117 | context, append the local searchable terms, and return the result. 118 | """ 119 | 120 | searchables = self._define_searchables() 121 | for child in self._children: 122 | searchables.extend(child.get_searchable()) 123 | for searchable in searchables: 124 | searchable.add_context(self) 125 | return searchables 126 | 127 | def _define_searchables(self): 128 | """ 129 | Abstract method that should be implemented in each child object. 130 | It is here that all of the searchable instances are defined for 131 | the object. They are placed in a list and returned as the result 132 | :rtype : list 133 | """ 134 | result = [] 135 | # result.append(Searchable(keyword, value, relationship)) 136 | return result -------------------------------------------------------------------------------- /nxtoolkit/nxcounters.py: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # # 3 | # Copyright (c) 2015 Cisco Systems # 4 | # All Rights Reserved. # 5 | # # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 7 | # not use this file except in compliance with the License. You may obtain # 8 | # a copy of the License at # 9 | # # 10 | # http://www.apache.org/licenses/LICENSE-2.0 # 11 | # # 12 | # Unless required by applicable law or agreed to in writing, software # 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 15 | # License for the specific language governing permissions and limitations # 16 | # under the License. # 17 | # # 18 | ################################################################################ 19 | """ 20 | NX Toolkit module for counter and stats objects 21 | """ 22 | 23 | import re 24 | 25 | 26 | class InterfaceStats(object): 27 | """ 28 | This class defines interface statistics. It will provide methods to 29 | retrieve the stats. The stats are returned as a dictionary with the 30 | following structure: 31 | 32 | stats= {:{:value}} 33 | 34 | stats are gathered and summed up in time intervals or granularities. 35 | For each granularity there are a set of time periods identified by 36 | the field. The current stats are stored in period 0. These 37 | stats are zeroed at the beginning of the time interval and are updated 38 | at a smaller time interval depending on the granularity. Historical 39 | statistics have periods that are greater than 0. The number of historical 40 | stats to keep is determined by the monitoring policy and may be specific 41 | to a particular counter family. 42 | 43 | The counter families are as follows: 'egrTotal', 'egrBytes', 'egrPkts', 44 | 'egrDropPkts', 'ingrBytes', 'ingrPkts', 'ingrTotal', 'ingrDropPkts', 45 | 'ingrUnkBytes','ingrUnkPkts', 'ingrStorm'. 46 | 47 | The granularities are: '5min', '15min', '1h', '1d', '1w', '1mo', 48 | '1qtr', and '1year'. 49 | 50 | For each counter family/granularity/period there are several counter 51 | values retained. The best way to see a list of these counters is to 52 | print the keys of the dictionary. 53 | """ 54 | def __init__(self, parent, interfaceDn): 55 | self._parent = parent 56 | self._interfaceDn = interfaceDn 57 | 58 | @classmethod 59 | def get_all_ports(cls, session, period=None): 60 | """ 61 | This method will get all the interface stats for all of the interfaces and return it as a dictionary indexed by the interface id. 62 | This method is optimized to minimize the traffic to and from the Switch and is intended to typically be used with the period specified 63 | so that only the necessary stats are pulled. Note that it will pull the stats for ALL the interfaces. This may have latency 64 | implications. 65 | 66 | :param session: Session to use when accessing the Switch 67 | :param period: Epoch or period to retrieve - all are retrieved if this is not specified 68 | 69 | :returns: Dictionary of counters. Format is {{: 70 | {:{:{:value}}}}} 71 | """ 72 | 73 | if period: 74 | if (period < 1): 75 | raise ValueError('Counter epoch/period value of 0 not yet implemented') 76 | mo_query_url = '/api/class/l1PhysIf.json?&rsp-subtree-include=stats&rsp-subtree-' \ 77 | 'class=statsHist&rsp-subtree-filter=eq(statsHist.index,"'+str(period-1)+'")' 78 | else: 79 | mo_query_url = '/api/class/l1PhysIf.json?&rsp-subtree-include=stats&rsp-subtree-class=statsHist' 80 | ret = session.get(mo_query_url) 81 | data = ret.json()['imdata'] 82 | 83 | result = {} 84 | for interface in data: 85 | if 'children' in interface['l1PhysIf']: 86 | port_id = cls._parseDn2PortId(interface['l1PhysIf']['attributes']['dn']) 87 | port_stats = InterfaceStats._process_data(interface) 88 | result[port_id] = port_stats 89 | return result 90 | 91 | @classmethod 92 | def _parseDn2PortId(cls, dn): 93 | """ 94 | This will parse the dn and return a port_id string. 95 | 96 | Handles DNs that look like the following: 97 | topology/pod-1/node-103/sys/phys-[eth1/12] 98 | and returns 1/103/1/12. 99 | """ 100 | name = dn.split('/') 101 | pod = name[1].split('-')[1] 102 | node = name[2].split('-')[1] 103 | module = name[4].split('[')[1] 104 | interface_type = module[:3] 105 | module = module[3:] 106 | port = name[5].split(']')[0] 107 | 108 | return '{0}/{1}/{2}/{3}'.format(pod, node, module, port) 109 | 110 | def get(self, session=None, period=None): 111 | """ 112 | Retrieve the count dictionary. This method will read in all the 113 | counters and return them as a dictionary. 114 | 115 | :param session: Session to use when accessing the Switch 116 | 117 | :returns: Dictionary of counters. Format is {: {:value}} 118 | """ 119 | result = {} 120 | if not session: 121 | session = self._parent._session 122 | 123 | mo_query_url = '/api/mo/' + self._interfaceDn + '.json?rsp-subtree=full&rsp-subtree-include=stats' 124 | ret = session.get(mo_query_url) 125 | data = ret.json()['imdata'] 126 | 127 | result = InterfaceStats._process_data(data[0]) 128 | # store the result to be accessed by the retrieve method 129 | self.result = result 130 | return result 131 | 132 | @staticmethod 133 | def _process_data(data): 134 | result = {} 135 | # List of attributes to be skipped 136 | skip_attr_list = ['childAction', 'clearTs', 'rn', 'status', 'babble'] 137 | if data: 138 | if 'children' in data['l1PhysIf']: 139 | children = data['l1PhysIf']['children'] 140 | for grandchildren in children: 141 | for count in grandchildren: 142 | if count in ['rmonIfIn', 'rmonIfOut', 'rmonEtherStats']: 143 | result[count] = {} 144 | result[count]['totalPkts'] = 0 145 | counterAttr = grandchildren[count]['attributes'] 146 | for att in counterAttr: 147 | if att in ['broadcastPkts', 'multicastPkts', 'ucastPkts']: 148 | result[count]['totalPkts'] += int(counterAttr[att]) 149 | result[count][att] = int(counterAttr[att]) 150 | elif att in ['octetRate', 'packetRate', 'dropEvents', 'ifdowndrop']: 151 | result[count][att] = float(counterAttr[att]) 152 | elif att not in skip_attr_list: 153 | result[count][att] = counterAttr[att] 154 | 155 | return result 156 | 157 | def retrieve(self, countFamily, countName): 158 | """ 159 | This will return the requested count from stats that were loaded with 160 | the previous get(). It will return 0 for counts that don't exist or 161 | None for time stamps that don't exist. 162 | 163 | Note that this method will not access the Switch, it will only work on 164 | data that was previously loaded with a get(). 165 | 166 | :param countFamily: The counter family string. Examples are 167 | 'egrTotal', 'ingrDropPkts, etc. 168 | :param countName: Name of the actual counter. Examples are 169 | 'unicastPer', 'unicastRate', etc. Counter 170 | names are unique per counter family. 171 | 172 | :returns: integer, float or None. If the counter is not present, 173 | it will return 0. 174 | """ 175 | 176 | if countName in ['octetRate', 'packetRate', 'dropEvents', 'ifdowndrop']: 177 | result = 0.0 178 | else: 179 | result = 0 180 | if countFamily in self.result: 181 | if countName in self.result[countFamily]: 182 | result = self.result[countFamily][countName] 183 | return result 184 | 185 | -------------------------------------------------------------------------------- /nxtoolkit/nxtoolkitlib.py: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # # 3 | # Copyright (c) 2015 Cisco Systems # 4 | # All Rights Reserved. # 5 | # # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 7 | # not use this file except in compliance with the License. You may obtain # 8 | # a copy of the License at # 9 | # # 10 | # http://www.apache.org/licenses/LICENSE-2.0 # 11 | # # 12 | # Unless required by applicable law or agreed to in writing, software # 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 15 | # License for the specific language governing permissions and limitations # 16 | # under the License. # 17 | # # 18 | ################################################################################ 19 | """ 20 | Used to get the NX and MySQL login credentials from the command 21 | line (--help gives usage). 22 | 23 | The login credentials are taken in the following order 24 | 25 | * Command line arguments 26 | * Environment variables 27 | * File named credentials.py 28 | * From an interactive prompt 29 | 30 | These are done in a per credential basis so it is possible to specify only 31 | some of the arguments. For instance, the username and URL can be specified 32 | in credentials.py but the password can be taken from the user through the 33 | interactive prompt. Another example is using the command line argument to 34 | override the URL specified in credentials.py to temporarily connect to a 35 | different NX. 36 | """ 37 | import argparse 38 | import os 39 | import sys 40 | import getpass 41 | 42 | 43 | class Credentials(object): 44 | """ 45 | Main class to derive the credentials from the user 46 | """ 47 | def __init__(self, qualifier='switch', description=''): 48 | def set_default(key): 49 | """ 50 | Check for the following: 51 | - environmental variables 52 | - credentials.py file 53 | """ 54 | if 'NX_' + key.upper() in os.environ.keys(): 55 | return os.environ['NX_' + key.upper()] 56 | else: 57 | try: 58 | import credentials 59 | except ImportError: 60 | return None 61 | try: 62 | default = credentials.__getattribute__(key.upper()) 63 | return default 64 | except AttributeError: 65 | return None 66 | 67 | if isinstance(qualifier, str): 68 | qualifier = (qualifier) 69 | self._qualifier = qualifier 70 | self._args = None 71 | self._parser = argparse.ArgumentParser(description=description) 72 | if 'switch' in qualifier: 73 | DEFAULT_URL = set_default('url') 74 | DEFAULT_LOGIN = set_default('login') 75 | DEFAULT_PASSWORD = set_default('password') 76 | self._parser.add_argument('-u', '--url', 77 | default=DEFAULT_URL, 78 | help='NX IP address.') 79 | self._parser.add_argument('-l', '--login', 80 | default=DEFAULT_LOGIN, 81 | help='NX login ID.') 82 | self._parser.add_argument('-p', '--password', 83 | default=DEFAULT_PASSWORD, 84 | help='NX login password.') 85 | self._parser.add_argument('--snapshotfiles', nargs='+', 86 | help='NX configuration files') 87 | if 'mysql' in qualifier: 88 | DEFAULT_MYSQL_IP = set_default('mysqlip') 89 | DEFAULT_MYSQL_LOGIN = set_default('mysqllogin') 90 | DEFAULT_MYSQL_PASSWORD = set_default('mysqlpassword') 91 | self._parser.add_argument('-i', '--mysqlip', 92 | default=DEFAULT_MYSQL_IP, 93 | help='MySQL IP address.') 94 | self._parser.add_argument('-a', '--mysqllogin', 95 | default=DEFAULT_MYSQL_LOGIN, 96 | help='MySQL login ID.') 97 | self._parser.add_argument('-s', '--mysqlpassword', 98 | default=DEFAULT_MYSQL_PASSWORD, 99 | help='MySQL login password.') 100 | if 'server' in qualifier: 101 | DEFAULT_PORT = '5000' 102 | DEFAULT_IPADDRESS = '127.0.0.1' 103 | self._parser.add_argument('--ip', 104 | default=DEFAULT_IPADDRESS, 105 | help='IP address to listen on.') 106 | self._parser.add_argument('--port', 107 | default=DEFAULT_PORT, 108 | help='Port number to listen on.') 109 | self._parser.add_argument('--test', 110 | action='store_true', default=False, 111 | help='Enable functions for lab testing.') 112 | 113 | @staticmethod 114 | def _get_from_user(prompt): 115 | """ 116 | Get the input from the user through interactive prompt. 117 | Use raw_input or input based on the Python version. 118 | """ 119 | try: 120 | resp = raw_input(prompt) 121 | except NameError: 122 | resp = input(prompt) 123 | return resp 124 | 125 | @staticmethod 126 | def _get_password(prompt): 127 | """ 128 | Get the password from the user through interactive prompt. 129 | Using this will ensure that the password is not displayed as 130 | it is typed. 131 | """ 132 | return getpass.getpass(prompt) 133 | 134 | def get(self): 135 | """ 136 | Get the arguments and verify them 137 | """ 138 | self._args = self._parser.parse_args() 139 | self.verify() 140 | return self._args 141 | 142 | def add_argument(self, *args, **kwargs): 143 | """ 144 | Pass through function to allow the underlying parser to be 145 | extended. 146 | """ 147 | self._parser.add_argument(*args, **kwargs) 148 | 149 | def add_mutually_exclusive_group(self, *args, **kwargs): 150 | """ 151 | Pass through function to allow the underlying parser to be 152 | extended. 153 | """ 154 | return self._parser.add_mutually_exclusive_group(*args, **kwargs) 155 | 156 | def add_argument_group(self, *args, **kwargs): 157 | """ 158 | Pass through function to allow the underlying parser to be 159 | extended. 160 | """ 161 | return self._parser.add_argument_group(*args, **kwargs) 162 | 163 | def print_help(self, *args, **kwargs): 164 | """ 165 | Pass through function to allow the underlying parser to be 166 | extended. 167 | """ 168 | return self._parser.print_help(*args, **kwargs) 169 | 170 | def verify(self): 171 | """ 172 | Verify that the arguments have been passed in some way. If not, 173 | ask the user through interactive prompt. 174 | """ 175 | if 'switch' in self._qualifier and self._args.snapshotfiles is None: 176 | if self._args.login is None: 177 | self._args.login = self._get_from_user('NX login username: ') 178 | if self._args.url is None: 179 | self._args.url = self._get_from_user('NX URL: ') 180 | if self._args.password is None: 181 | self._args.password = self._get_password('NX Password: ') 182 | if 'mysql' in self._qualifier: 183 | if self._args.mysqlip is None: 184 | self._args.mysqlip = self._get_from_user('MySQL IP address: ') 185 | if self._args.mysqllogin is None: 186 | prompt = 'MySQL login username: ' 187 | self._args.mysqllogin = self._get_from_user(prompt) 188 | if self._args.mysqlpassword is None: 189 | prompt = 'MySQL Password: ' 190 | self._args.mysqlpassword = self._get_password(prompt) 191 | -------------------------------------------------------------------------------- /samples/README.md: -------------------------------------------------------------------------------- 1 | # NX Toolkit Samples # 2 | 3 | This directory contains sample scripts that use the python library. 4 | 5 | ### Set up ### 6 | 7 | In order to use the examples in this directory, it is important to set the PYTHONPATH variable to include the path to the NX toolkit or have installed the nxtoolkit using setup.py. 8 | 9 | ### credentials.py ### 10 | Many of the samples in this directory use the file credentials.py to login to the Switch. Before running, edit the credentials.py with the username, password, and IP address for your environment. 11 | 12 | -------------------------------------------------------------------------------- /samples/nx-config-arp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and Configure Arp 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and Configure Arp.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | ''' Login to Switch ''' 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | arp = NX.ARP() # Create ARP instance 48 | arp.set_timeout('100') 49 | 50 | ''' Push ARP configuration to the switch ''' 51 | resp = session.push_to_switch(arp.get_url(), arp.get_json()) 52 | if not resp.ok: 53 | print resp.text 54 | print ('Could not push to Switch') 55 | exit(0) 56 | 57 | # To remove the configuration do the post request without setting timeout 58 | 59 | arp_data = NX.ARP.get(session) 60 | print "IP ARP Timeout: ", arp_data.timeout 61 | 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /samples/nx-config-bootNxos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and set the boot variable 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and set the boot variable.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create Boot instance 48 | boot = NX.BootNxos('n9000-dk9.7.0.3.I2.0.551') 49 | 50 | # Push boot configuration to the switch 51 | resp = session.push_to_switch(boot.get_url(), boot.get_json()) 52 | if not resp.ok: 53 | print resp.text 54 | print ('Could not set the boot variable') 55 | exit(0) 56 | 57 | boot_nxos = boot.get(session) 58 | print "Current Boot Variables:" 59 | print "Sup1" 60 | print "NXOS variable = ", boot_nxos.sup1 61 | print "Boot Variables on next reload:" 62 | print "Sup2" 63 | print "NXOS variable = ", boot_nxos.sup2 64 | 65 | # Uncomment below lines to delete unset the boot variable 66 | ''' 67 | resp = session.delete(boot.get_url()) 68 | if not resp.ok: 69 | print('%% Could not delete from Switch') 70 | sys.exit(0) 71 | ''' 72 | 73 | 74 | if __name__ == '__main__': 75 | main() 76 | -------------------------------------------------------------------------------- /samples/nx-config-dhcp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure DHCP relay 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and config DHCP relay on an interface.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create DHCP instance 48 | dhcp = NX.Dhcp() 49 | dhcp.set_v4relay_st('yes') 50 | dhcp.set_v6relay_st('no') 51 | 52 | relay1 = NX.DhcpRelay('eth2/1') 53 | relay1.add_relay_address('1.1.1.1') 54 | relay1.add_relay_address('23ad:33::faa', 'test_vrf') 55 | dhcp.add_relay(relay1) 56 | 57 | relay2 = NX.DhcpRelay('eth2/2') 58 | relay2.add_relay_address('2.2.2.1') 59 | relay2.add_relay_address('23ad:33::fbb', 'test_vrf') 60 | dhcp.add_relay(relay2) 61 | 62 | # Push dhcp configuration to the switch 63 | resp = session.push_to_switch(dhcp.get_url(), dhcp.get_json()) 64 | if not resp.ok: 65 | print resp.text 66 | print ('Could not create port-channel') 67 | exit(0) 68 | 69 | for data in dhcp.get(session): 70 | template = "{0:18} {1:18} {2:18}" 71 | print template.format("Interface", "Relay Address", "VRF Name") 72 | print template.format("----------", "----------", "----------") 73 | 74 | for relay in data.dhcp_relays: 75 | for (address, vrf) in zip(relay.relay_address, relay.vrf_name): 76 | print template.format(relay.interface, address, vrf) 77 | 78 | # Uncomment below lines to delete Dhcp Relay configuration 79 | ''' 80 | resp = session.delete(dhcp.get_url()) 81 | if not resp.ok: 82 | print('%% Could not configure the Switch') 83 | sys.exit(0) 84 | ''' 85 | 86 | if __name__ == '__main__': 87 | main() -------------------------------------------------------------------------------- /samples/nx-config-dns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure DNS 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and configure DNS.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create DNS instance 48 | dns = NX.DNS() 49 | dns.enable_lookup() 50 | 51 | prof1 = NX.DnsProfile() 52 | 53 | dns_provider = NX.DnsProvider('1.1.1.2') 54 | prof1.add(dns_provider) 55 | 56 | dns_domain = NX.DnsDom('name') 57 | prof1.add(dns_domain) 58 | 59 | dns_dmn_ext = NX.DnsDomExt('name1') 60 | prof1.add(dns_dmn_ext) 61 | 62 | dns_host = NX.DnsHost('name2', '1:1::12') 63 | prof1.add(dns_host) 64 | 65 | # Create VRF instance 66 | vrf1 = NX.DnsVrf('test_vrf1') 67 | vrf2 = NX.DnsVrf('test_vrf2') 68 | 69 | vrf1.use_in(dns_provider) 70 | vrf2.use_in(dns_dmn_ext) 71 | 72 | # Add VRF to DNS 73 | prof1.add(vrf1) 74 | prof1.add(vrf2) 75 | 76 | dns.add_profile(prof1) 77 | 78 | # Push DNS configuration to the switch 79 | resp = session.push_to_switch(dns.get_url(), dns.get_json()) 80 | if not resp.ok: 81 | print resp.text 82 | print ('Could not configure DNS') 83 | exit(0) 84 | 85 | # Uncomment below lines to delete the dns configuration 86 | ''' 87 | resp = session.delete(dns.get_url()) 88 | if not resp.ok: 89 | print('%% Could not delete from Switch') 90 | sys.exit(0) 91 | ''' 92 | 93 | 94 | if __name__ == '__main__': 95 | main() -------------------------------------------------------------------------------- /samples/nx-config-feature.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and enable features 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | def main(): 27 | """ 28 | Main execution routine 29 | 30 | :return: None 31 | """ 32 | # Take login credentials from the command line if provided 33 | # Otherwise, take them from your environment variables file ~/.profile 34 | description = '''Simple application that logs on to the 35 | Switch and enable features''' 36 | creds = NX.Credentials('switch', description) 37 | args = creds.get() 38 | 39 | # Login to Switch 40 | session = NX.Session(args.url, args.login, args.password) 41 | 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | #Create Feature Base object 48 | feature = NX.Feature(session) 49 | 50 | feature.enable('bgp') 51 | feature.enable('dhcp') 52 | feature.enable('interface-vlan') 53 | feature.enable('udld') 54 | feature.enable('vrrp') 55 | feature.enable('nxapi') 56 | feature.enable('tacacsplus') 57 | feature.enable('lacp') 58 | 59 | # Push entire configuration to switch 60 | resp = session.push_to_switch(feature.get_url(), feature.get_json()) 61 | if not resp.ok: 62 | print('%% Error: Could not push configuration to Switch') 63 | print(resp.text) 64 | 65 | template = "{0:20} {1:16} {2:16}" 66 | print(template.format("Feature Name", "Instance", "state")) 67 | print(template.format("------------", "------------", 68 | "------------")) 69 | 70 | 71 | for data in feature.get(): 72 | print(template.format(data.name, data.instance, data.admin_st)) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() 77 | 78 | -------------------------------------------------------------------------------- /samples/nx-config-icmp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application to login into the switch and configure icmp 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | def main(): 27 | """ 28 | Main execution routine 29 | 30 | :return: None 31 | """ 32 | # Take login credentials from the command line if provided 33 | # Otherwise, take them from your environment variables file ~/.profile 34 | description = '''Simple application to login into the switch and configure 35 | icmp.''' 36 | creds = NX.Credentials('switch', description) 37 | args = creds.get() 38 | 39 | # Login to Switch 40 | session = NX.Session(args.url, args.login, args.password) 41 | 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create an instance of interface 48 | int1 = NX.Interface('eth1/20') 49 | int1.set_layer('Layer3') 50 | 51 | # Push the configuration to the switch to make the interface L3 52 | resp = session.push_to_switch(int1.get_url(), int1.get_json()) 53 | if not resp.ok: 54 | print ('%% Could not push to Switch') 55 | print resp.text 56 | sys.exit(0) 57 | 58 | # Create an instance of icmp 59 | icmp = NX.ICMP('v4', int1, 'redirect') 60 | 61 | resp = session.push_to_switch(icmp.get_url(), icmp.get_json()) 62 | if not resp.ok: 63 | print ('%% Could not push to Switch') 64 | print resp.text 65 | sys.exit(0) 66 | 67 | # Uncomment below lines to delete Icmp from the given interface 68 | ''' 69 | resp = session.delete(icmp.get_url()) 70 | if not resp.ok: 71 | print ('%% Could not delete from Switch') 72 | print resp.text 73 | sys.exit(0) 74 | ''' 75 | 76 | # To get the redirection state 77 | icmps = NX.ICMP.get(session) 78 | 79 | template = "{0:16} {1:16} {2:16}" 80 | print template.format("Interface/Vlan", "Redirect state", "Version") 81 | print template.format("---------------", "---------------", "---------------") 82 | for icmp in icmps: 83 | print template.format(icmp.id, icmp.status, icmp.version) 84 | 85 | 86 | 87 | if __name__ == '__main__': 88 | main() -------------------------------------------------------------------------------- /samples/nx-config-ifmgr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure interface breakout. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch and 36 | configure interface breakout.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | brkout = NX.InterfaceBreakout() 48 | 49 | module1 = NX.BreakoutModule('1') 50 | module1.add_port_map('1', '10g-4x') 51 | module1.add_port_map('2', '10g-4x') 52 | 53 | module2 = NX.BreakoutModule('2') 54 | module2.add_port_map('1', '10g-4x') 55 | 56 | brkout.add_module(module1) 57 | brkout.add_module(module2) 58 | 59 | resp = session.push_to_switch(brkout.get_url(), brkout.get_json()) 60 | if not resp.ok: 61 | print resp.text 62 | print('%% Could not configure the Switch') 63 | sys.exit(0) 64 | 65 | # Display all the data 66 | brk = NX.InterfaceBreakout.get(session) 67 | 68 | # Get list of BreakoutModule object 69 | modules = brk.modules.get() 70 | for module in modules: 71 | print "Module %s:\n========" % (module.module_num) 72 | # Get list of breakout ports under module 73 | ports = module.ports.get() 74 | for port in ports: 75 | print "Port:", port.id 76 | print "Map :", port.map 77 | print "" 78 | 79 | # Uncomment below lines to delete breakout configuration for port 80 | # 1 of module 1 81 | ''' 82 | resp = session.delete(brkout.get_delete_url(module='1', port='1')) 83 | if not resp.ok: 84 | print('%% Could not configure the Switch') 85 | sys.exit(0) 86 | ''' 87 | 88 | # Uncomment below lines to delete all the breakout module 89 | ''' 90 | resp = session.delete(brkout.get_url()) 91 | if not resp.ok: 92 | print('%% Could not configure the Switch') 93 | sys.exit(0) 94 | ''' 95 | 96 | 97 | if __name__ == '__main__': 98 | main() 99 | -------------------------------------------------------------------------------- /samples/nx-config-interface.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure the Interfaces. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch and 36 | configure the Interfaces.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | int1 = NX.Interface('eth1/6') 48 | int2 = NX.Interface('eth1/7') 49 | 50 | # ConfigInterfacs object is used to configure multiple 51 | # interfaces at a time (No need of multiple REST calls) 52 | # Note: Using Interface object also an interface can be configured 53 | config = NX.ConfigInterfaces() 54 | 55 | # Adding interfaces to be configured 56 | config.add_interface(int1) 57 | config.add_interface(int2) 58 | 59 | # Setting interface attributes 60 | # Note: if attributes are not set, then default values will be used 61 | int1.set_admin_status('up') 62 | int1.set_layer('Layer2') 63 | int1.set_duplex('auto') 64 | int1.set_link_log('default') 65 | int1.set_mode('access') 66 | int1.set_speed('10G') 67 | int1.set_access_vlan('vlan-100') 68 | int1.set_trunk_log('default') 69 | int1.set_link_log('default') 70 | 71 | # Push entire configuration to the switch 72 | # Note:To configure only one interface use int1.get_url() & int1.get_json() 73 | resp = session.push_to_switch(config.get_url(), config.get_json()) 74 | if not resp.ok: 75 | print ('%% Could not push to Switch') 76 | print resp.text 77 | sys.exit(0) 78 | 79 | ethpm = NX.Ethpm() 80 | ethpm.set_default_admin_st('up') 81 | ethpm.set_default_layer('Layer2') 82 | ethpm.set_jumbomtu('9216') 83 | ethpm.set_unsupported_transceiver('yes') 84 | 85 | resp = session.push_to_switch(ethpm.get_url(), ethpm.get_json()) 86 | if not resp.ok: 87 | print ('%% Could not push to Switch') 88 | print resp.text 89 | sys.exit(0) 90 | 91 | # Uncomment below lines to get the configured ethpm 92 | ''' 93 | resp = NX.Ethpm.get(session) 94 | print "Ethpm :\n=======" 95 | print "Admin status :", resp.get_default_admin_st() 96 | print "Default layer :", resp.get_default_layer() 97 | print "Jumbo mtu :", resp.get_jumbomtu() 98 | print "Unsupported-transceiver: :", resp.get_unsupported_transceiver() 99 | ''' 100 | 101 | if __name__ == '__main__': 102 | main() 103 | -------------------------------------------------------------------------------- /samples/nx-config-ipv4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure ipv4 on the 22 | Interfaces. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the Switch and 37 | configure ipv4 on the Interfaces.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Creating interface objects 49 | # Note: interfaces should be L3 interface 50 | int1 = NX.Interface('eth1/20') 51 | 52 | # Create a L3 port channel 53 | pc1 = NX.PortChannel('211', layer='Layer3') 54 | 55 | # Create the port channel in the switch 56 | # Note:(port channel should be exist in the switch before 57 | # assigning IPv6 to it) 58 | resp = session.push_to_switch(pc1.get_url(), pc1.get_json()) 59 | if not resp.ok: 60 | print ('%% Could create port channel in the Switch') 61 | print resp.text 62 | sys.exit(0) 63 | 64 | # Create IPv4 instance 65 | ipv4 = NX.IP() 66 | 67 | # Enable ip directed broadcast on the interface 68 | ipv4.enable_directed_broadcast(int1) 69 | 70 | # Add interfaces 71 | ipv4.add_interface_address(int1, '1.1.1.1/20') 72 | 73 | # Add port channel 74 | ipv4.add_interface_address(pc1, '3.3.3.211/13') 75 | 76 | # Configure IPv4 route and Nexthop information 77 | r1 = NX.IPRoute('4.4.4.4/32') 78 | r1.add_next_hop('5.5.5.5', int1, vrf='default', track_id='0', tag='1') 79 | r1.add_next_hop('7.7.7.7', pc1, vrf='default', track_id='1', tag='2') 80 | 81 | # Add route to IPv4 82 | ipv4.add_route(r1) 83 | 84 | print ipv4.get_url() 85 | print ipv4.get_json() 86 | resp = session.push_to_switch(ipv4.get_url(), ipv4.get_json()) 87 | if not resp.ok: 88 | print ('%% Could not push to Switch.') 89 | print resp.text 90 | sys.exit(0) 91 | 92 | # Uncomment below to delete the resources 93 | ''' 94 | # Delete IP route 95 | resp = session.delete(r1.get_delete_url()) 96 | if not resp.ok: 97 | print ('%% Could not delete from Switch') 98 | print resp.text 99 | sys.exit(0) 100 | 101 | # Delete from interface 102 | resp = session.delete(ipv4.get_delete_url('eth1/20')) 103 | if not resp.ok: 104 | print ('%% Could not delete from Switch') 105 | print resp.text 106 | sys.exit(0) 107 | 108 | resp = session.delete(ipv4.get_url()) 109 | if not resp.ok: 110 | print ('%% Could not delete from Switch') 111 | print resp.text 112 | sys.exit(0) 113 | ''' 114 | 115 | 116 | if __name__ == '__main__': 117 | main() -------------------------------------------------------------------------------- /samples/nx-config-ipv6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure ipv6 on the 22 | Interfaces. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the Switch and 37 | configure ipv6 on the Interfaces.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Creating interface objects 49 | # Note: interfaces should be L3 interface 50 | int1 = NX.Interface('eth1/20') 51 | 52 | # Create a L3 port channel 53 | pc1 = NX.PortChannel('211', layer='Layer3') 54 | 55 | # Create the port channel in the switch 56 | # Note:(port channel should be exist in the switch before 57 | # assigning IPv6 to it) 58 | resp = session.push_to_switch(pc1.get_url(), pc1.get_json()) 59 | if not resp.ok: 60 | print ('%% Could create port channel in the Switch') 61 | print resp.text 62 | sys.exit(0) 63 | 64 | ipv6 = NX.IP('v6') 65 | 66 | # Add interfaces 67 | ipv6.add_interface_address(int1, '2004:0DB8::1/10', link_local='FE83::1') 68 | 69 | # Add port channel 70 | ipv6.add_interface_address(pc1, '2022:0DB8::1/13') 71 | 72 | # Configure IPv6 route and Nexthop information 73 | r1 = NX.IPRoute('2000:0::0/12', version='v6') 74 | r1.add_next_hop('234E:44::1', int1, vrf='default', track_id='0', tag='1') 75 | r1.add_next_hop('234E:44::4', pc1, vrf='default', track_id='1', tag='2') 76 | 77 | # Add route to IPv6 78 | ipv6.add_route(r1) 79 | 80 | print ipv6.get_url() 81 | print ipv6.get_json() 82 | resp = session.push_to_switch(ipv6.get_url(), ipv6.get_json()) 83 | if not resp.ok: 84 | print ('%% Could not push to Switch') 85 | print resp.text 86 | sys.exit(0) 87 | 88 | # Uncomment below to delete the resources 89 | ''' 90 | # Delete IPv6 route 91 | resp = session.delete(r1.get_delete_url()) 92 | if not resp.ok: 93 | print ('%% Could not delete from Switch') 94 | print resp.text 95 | sys.exit(0) 96 | 97 | # Delete from interface 98 | resp = session.delete(ipv4.get_delete_url('eth1/20')) 99 | if not resp.ok: 100 | print ('%% Could not delete from Switch') 101 | print resp.text 102 | sys.exit(0) 103 | 104 | resp = session.delete(ipv4.get_url()) 105 | if not resp.ok: 106 | print ('%% Could not delete from Switch') 107 | print resp.text 108 | sys.exit(0) 109 | ''' 110 | 111 | 112 | if __name__ == '__main__': 113 | main() -------------------------------------------------------------------------------- /samples/nx-config-lacp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application to login into the switch and configure lacp rate on 22 | the interface 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application to login into the switch and configure 36 | lacp rate on the interface''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | int1 = NX.Interface('eth1/2') 49 | lacp = NX.Lacp(rate='fast', interface=int1, session=session) 50 | 51 | # Push entire configuration to switch 52 | resp = session.push_to_switch(lacp.get_url(), lacp.get_json()) 53 | if not resp.ok: 54 | print('%% Error: Could not push configuration to Switch') 55 | print(resp.text) 56 | 57 | # Uncomment below line to get the configuration of all interfaces from 58 | # switch get_data = NX.Lacp.get(session) 59 | 60 | # Get LACP rate configuration from the switch 61 | get_data = NX.Lacp.get(session) 62 | template = "{0:16} {1:16}" 63 | print(template.format("Interface", "rate")) 64 | print(template.format("-------------", "-------------")) 65 | for data in get_data: 66 | print(template.format(data.interface, data.rate)) 67 | 68 | 69 | if __name__ == '__main__': 70 | main() 71 | -------------------------------------------------------------------------------- /samples/nx-config-nd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and Configure Neighbor Discovery 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and Configure Neighbor Discovery.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | ''' Login to Switch ''' 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | nd = NX.ND() # Create ND instance 48 | 49 | nd_int = NX.NdInterface('vlan123') 50 | nd_int.disable_redirect() 51 | nd_int.set_ra_interval('600') 52 | nd_int.set_prefix('2000::/12', '100', '99') 53 | 54 | nd.add(nd_int) 55 | 56 | print nd.get_json() 57 | ''' Push ND configuration to the switch ''' 58 | resp = session.push_to_switch(nd.get_url(), nd.get_json()) 59 | if not resp.ok: 60 | print resp.text 61 | print ('Could not push to Switch') 62 | exit(0) 63 | 64 | # Uncomment below lines to delete nd configuration of specific interface 65 | ''' 66 | nd_int = NX.NdInterface('vlan123') 67 | resp = session.delete(nd_int.get_url()) 68 | if not resp.ok: 69 | print('%% Could not delete from Switch') 70 | sys.exit(0) 71 | ''' 72 | 73 | template = "{0:20} {1:20} {2:20}" 74 | print template.format("Interface/Vlan", "Ra Interval", 75 | "Redirection State") 76 | print template.format("===============", "===============", 77 | "===============") 78 | nd_data = NX.ND.get(session) 79 | for int in nd_data.interfaces: 80 | print template.format(int.id, int.ra_interval, int.redirect_st) 81 | for prefix in int.prefixes: 82 | print ("Prefix Address:%s\tlifetime:%s\tpreferred lifetime:%s" 83 | % (prefix.address, prefix.lifetime, prefix.pref_lifetime)) 84 | print ("\n") 85 | 86 | # Uncomment below lines to get specific interface details 87 | ''' 88 | int_data = NX.NdInterface.get(session, 'vlan123') 89 | print template.format("Interface/Vlan", "Ra Interval", 90 | "Redirection State") 91 | print template.format("===============", "===============", 92 | "===============") 93 | print template.format(int_data.id, int_data.ra_interval, 94 | int_data.redirect_st) 95 | for prefix in int_data.prefixes: 96 | print ("Prefix Address:%s\tlifetime:%s\tpreferred lifetime:%s" 97 | % (prefix.address, prefix.lifetime, prefix.pref_lifetime)) 98 | ''' 99 | 100 | 101 | if __name__ == '__main__': 102 | main() 103 | -------------------------------------------------------------------------------- /samples/nx-config-port-channel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and create port channel 22 | and attach the specified interfaces to that port channel 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | import time 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = 'create port channel and attach interface' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # ConfigInterfaces instance is required to configure multiple port 48 | # channel at a time 49 | config = NX.ConfigInterfaces() 50 | 51 | 52 | # Create a POrtChannels object 53 | pc1 = NX.PortChannel('444') 54 | pc2 = NX.PortChannel('445') 55 | 56 | int1 = NX.Interface('eth1/5') 57 | int2 = NX.Interface('eth1/8') 58 | int3 = NX.Interface('eth1/9') 59 | 60 | # Attach interfaces to the port channel 61 | pc1.attach(int1) 62 | pc1.attach(int2) 63 | pc2.attach(int3) 64 | 65 | # Add port channels to the config object 66 | config.add_port_channel(pc1) 67 | config.add_port_channel(pc2) 68 | 69 | # Push/ create the port channel object to the switch 70 | # Note: To configure only single port channel use pc1.get_url() and 71 | # pc1.get_json() instead of config.get_url() and config.get_json() 72 | resp = session.push_to_switch(config.get_url(), config.get_json()) 73 | if not resp.ok: 74 | print resp.text 75 | print('%% Could not push to Switch: %s' % (resp.text)) 76 | sys.exit(0) 77 | 78 | 79 | # To delete the created port-channel (Uncomment below lines to 80 | # delete the port channel) 81 | # resp = session.delete(pc1.get_url()) 82 | #if not resp.ok: 83 | # print('%% Could not push to Switch: %s' % (resp.text)) 84 | # sys.exit(0) 85 | 86 | if __name__ == '__main__': 87 | main() 88 | -------------------------------------------------------------------------------- /samples/nx-config-rbac.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and Configure RBAC 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and Configure RBAC.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | ''' Login to Switch ''' 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | rbac = NX.RBAC() 48 | rbac.create_role('test-role') 49 | rbac.enable_pwd_strength_check() 50 | rbac.enable_pwd_secure_mode() 51 | rbac.set_pwd_max_length('127') 52 | rbac.set_pwd_min_length('4') 53 | 54 | #user = NX.AaaUser(name='test1', password='Test1', role='network-admin') 55 | user = NX.AaaUser(name='test1', password='Test1', role='network-admin', 56 | ssh_key='ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDczcGut' 57 | 'F5w331l0bNAeDSqKmwzLYYjElGIEogIE04rE0kX+CaWP/nDVEwETT' 58 | 'sKlp5w4gi0mA9/4kpk7gDGRCmAiNT8MWaTYt4ewGj+dZ+fbpUUf5t' 59 | 'v1DwLvxcQOoQ3qvxazOQWOLxwSW7zrJBpSokEtDNyY6BlsXP33q2h' 60 | 'gOBeAw==') 61 | 62 | rad_server = NX.AaaRadius() 63 | rad_server.set_retries('4') 64 | rad_server.set_timeout('30') 65 | rad_server.set_src_interface('lo0') 66 | rad_server.set_key(key='cisco', key_enc='7') 67 | rad_server.add_host('1.2.3.4', key='cisco', key_enc='7', timeout='5', 68 | retries='3') 69 | 70 | tacacs = NX.AaaTacacs() 71 | tacacs.set_deadtime('10') 72 | tacacs.set_timeout('20') 73 | tacacs.set_src_interface('mgmt 0') 74 | tacacs.set_key(key='cisco', key_enc='7') 75 | tacacs.add_host('1.2.3.3', key='cisco', key_enc='7', port='50', 76 | timeout='30') 77 | tacacs.add_group('tac1', vrf='management', deadtime='10', 78 | server='1.2.3.3') 79 | 80 | aaa = NX.AaaAaa() 81 | aaa.disable_auth_login('error-enable') 82 | aaa.enable_auth_login('ascii-authentication') 83 | aaa.set_auth_default_grp('tac1') #pass default group name 84 | aaa.set_author_default_grp() #pass default group name and cmd type 85 | aaa.set_acc_default_grp('tac1') #pass default group name 86 | 87 | rbac.add(user) 88 | rbac.add(rad_server) 89 | rbac.add(tacacs) 90 | rbac.add(aaa) 91 | 92 | print rbac.get_json() 93 | ''' Push RBAC configuration to the switch ''' 94 | resp = session.push_to_switch(rbac.get_url(), rbac.get_json()) 95 | if not resp.ok: 96 | print resp.text 97 | print ('Could not push to Switch') 98 | exit(0) 99 | 100 | 101 | # NOTE: Complete deletion of rbac configuration will delete admin 102 | #Configuration as well 103 | 104 | # Uncomment below two lines to delete specific role 105 | ''' 106 | rbac = NX.RBAC.get(session) 107 | resp = session.delete(rbac.roles[0].get_delete_url('test-role')) 108 | if not resp.ok: 109 | print resp.text 110 | print ('Could not push to Switch') 111 | exit(0) 112 | ''' 113 | 114 | # Uncomment the below lines to delete specific user 115 | ''' 116 | user = NX.AaaUser.get(session, 'test1') 117 | resp = session.delete(user.get_url()) 118 | if not resp.ok: 119 | print resp.text 120 | print ('Could not push to Switch') 121 | exit(0) 122 | ''' 123 | 124 | # Uncomment below two lines to delete radius-server host 125 | ''' 126 | radius = NX.AaaRadius.get(session) 127 | resp = session.delete(radius.servers[0].get_delete_url('1.2.3.4')) 128 | if not resp.ok: 129 | print resp.text 130 | print ('Could not push to Switch') 131 | exit(0) 132 | ''' 133 | 134 | # Uncomment below lines to delete tacacs-server details 135 | ''' 136 | tacacs = NX.AaaTacacs.get(session) 137 | # To delete tacacs-server host 138 | resp = session.delete(tacacs.servers[0].get_delete_url('1.2.3.3')) 139 | if not resp.ok: 140 | print resp.text 141 | print ('Could not push to Switch') 142 | exit(0) 143 | 144 | # To delete tacacs-server group 145 | resp = session.delete(tacacs.groups[0].get_delete_url('name')) 146 | if not resp.ok: 147 | print resp.text 148 | print ('Could not push to Switch') 149 | exit(0) 150 | 151 | # To delete tacacs-server group host 152 | resp = session.delete(tacacs.groups[0].grp_servers[0].get_delete_url( 153 | 'tac1', '1.2.3.3')) 154 | if not resp.ok: 155 | print resp.text 156 | print ('Could not push to Switch') 157 | exit(0) 158 | ''' 159 | 160 | 161 | if __name__ == '__main__': 162 | main() 163 | 164 | -------------------------------------------------------------------------------- /samples/nx-config-rpm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and Configure Route Processor 22 | Module 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the 37 | Switch and Configure Route Processor Module.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | ''' Login to Switch ''' 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | rpm = NX.RPM() 49 | 50 | route_map = NX.RouteMap('Test_route_map') 51 | # Note: Sequence number must not be present in the switch 52 | map_entry = NX.RouteMapEntry('permit', '10') 53 | map_entry.set_descr('This is test route-map') 54 | map_entry.match_rt_type('local') 55 | map_entry.match_rt_tag('200') 56 | map_entry.disable_nh_peer('v4') 57 | map_entry.set_next_hop('10.10.10.10') 58 | map_entry.set_next_hop('10:20::30:40') 59 | map_entry.set_local_pref('1000') 60 | map_entry.set_origin('incomplete') 61 | map_entry.set_comm_list('test-community', 'delete') 62 | 63 | map_entry.match_as_path('test-access-list') 64 | map_entry.match_pfxlistv4('test-prefix-v4') 65 | map_entry.match_pfxlistv6('test-prefix-v6') 66 | map_entry.match_comm('test-community', 'exact') 67 | 68 | map_entry.set_comm('additive,internet,local-AS,no-advertise,1:2') 69 | 70 | route_map.add(map_entry) 71 | 72 | pfx_v4 = NX.PrefixList('test_prefix') 73 | # Note: Sequence number must not be present in the switch 74 | pfx_v4.set_prefix('1.2.3.4/8', 'permit', '10') 75 | 76 | pfx_v6 = NX.PrefixList('test_prefix', 'v6') 77 | # Note: Sequence number must not be present in the switch 78 | pfx_v6.set_prefix('fff:1::2:3/8', 'permit', '10') 79 | 80 | as_path = NX.AsPath('testAccList') 81 | as_path.set_access_list('permit', '1234') 82 | 83 | comm = NX.CommunityList('comrule', 'standard') 84 | # Note: Sequence number must not be present in the switch 85 | comm_entry = NX.CommunityEntry('permit', 86 | 'internet,local-AS,no-advertise,no-export,1:2', '5') 87 | comm.add(comm_entry) 88 | 89 | rpm.add(route_map) 90 | rpm.add(pfx_v4) 91 | rpm.add(pfx_v6) 92 | rpm.add(as_path) 93 | rpm.add(comm) 94 | print rpm.get_json() 95 | 96 | ''' Push RPM configuration to the switch ''' 97 | resp = session.push_to_switch(rpm.get_url(), rpm.get_json()) 98 | if not resp.ok: 99 | print resp.text 100 | print ('Could not push to Switch') 101 | exit(0) 102 | 103 | # Uncomment below two lines to delete specific route-map 104 | ''' 105 | resp = session.delete(route_map.get_url()) 106 | if not resp.ok: 107 | print resp.text 108 | print ('Could not push to Switch') 109 | exit(0) 110 | ''' 111 | 112 | # Uncomment below two lines to delete specific ip prefix-list 113 | ''' 114 | resp = session.delete(pfx_v4.get_url()) 115 | if not resp.ok: 116 | print resp.text 117 | print ('Could not push to Switch') 118 | exit(0) 119 | ''' 120 | 121 | # Uncomment below two lines to delete specific ipv6 prefix-list 122 | ''' 123 | print pfx_v6.get_url() 124 | resp = session.delete(pfx_v6.get_url()) 125 | if not resp.ok: 126 | print resp.text 127 | print ('Could not push to Switch') 128 | exit(0) 129 | ''' 130 | 131 | # Uncomment below two lines to delete specific AsPath access-list 132 | ''' 133 | resp = session.delete(as_path.get_url()) 134 | if not resp.ok: 135 | print resp.text 136 | print ('Could not push to Switch') 137 | exit(0) 138 | ''' 139 | 140 | # Uncomment below two lines to delete specific community-list 141 | ''' 142 | resp = session.delete(comm.get_url()) 143 | if not resp.ok: 144 | print resp.text 145 | print ('Could not push to Switch') 146 | exit(0) 147 | ''' 148 | 149 | 150 | if __name__ == '__main__': 151 | main() 152 | -------------------------------------------------------------------------------- /samples/nx-config-stp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and Configure STP 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and Configure STP.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | ''' Login to Switch ''' 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | stp = NX.STP() # Create STP instance 48 | stp.set_mode('pvrst') 49 | 50 | stp.add_port_type('bpdufilter') 51 | stp.add_port_type('bpduguard') 52 | stp.add_port_type('edge') 53 | stp.add_port_type('network') 54 | 55 | mst_etity = NX.StpMst() 56 | mst_etity.set_simulate('disabled') 57 | 58 | vlan = NX.StpVlan('222') 59 | vlan.set_admin_st('enabled') 60 | vlan.set_bdg_priority('12288') 61 | 62 | int = NX.Interface('eth1/20') 63 | i_face = NX.StpInterface(int) 64 | 65 | i_face.set_mode('network') # Mode can be network/edge/normal only for l2 66 | # interface 67 | 68 | stp.add(mst_etity) 69 | stp.add(vlan) 70 | stp.add(i_face) 71 | 72 | ''' Push STP configuration to the switch ''' 73 | resp = session.push_to_switch(stp.get_url(), stp.get_json()) 74 | if not resp.ok: 75 | print resp.text 76 | print ('Could not push to Switch') 77 | exit(0) 78 | 79 | ''' 80 | # Delete interface STP configuration 81 | resp = session.delete(i_face.get_url()) 82 | if not resp.ok: 83 | print('%% Could not delete from Switch') 84 | sys.exit(0) 85 | 86 | 87 | # Uncomment below lines to delete all the STP configuration 88 | resp = session.delete(stp.get_url()) 89 | if not resp.ok: 90 | print('%% Could not delete from Switch') 91 | sys.exit(0) 92 | ''' 93 | 94 | # Get the STP details 95 | data = NX.STP.get(session) 96 | print "STP Mode:\t", data.mode 97 | print "STP Port type:\t", data.port_type 98 | for mst in data.msts: 99 | print "MSt state:\t", mst.simulate 100 | print "Hello time:\t", mst.hello_time 101 | print "Forward time:\t", mst.fwd_delay 102 | print "Maximum age:\t", mst.max_age 103 | 104 | template = "{0:14} {1:14} {2:14} {3:14}" 105 | print (template.format("Interface", "Mode", "Priority", "Cost")) 106 | print (template.format("-----------", "-----------", "-----------", 107 | "-----------")) 108 | for i_face in data.i_faces: 109 | print (template.format(i_face.id, i_face.mode, i_face.priority, 110 | i_face.cost)) 111 | 112 | for vlan in data.vlans: 113 | print "\n" 114 | print ("Vlan-%s, Admin State: %s, Protocol: %s" % (vlan.id, 115 | vlan.admin_st, 116 | vlan.protocol)) 117 | print ("Root:: Address: %s\tPriority: %s\tCost: %s\tPort Number: %s" % 118 | (vlan.root_addr, vlan.root_priority, vlan.root_cost, 119 | vlan.root_port_no)) 120 | print ("Bridge:: Address: %s\tPriority: %s" % (vlan.bdg_addr, 121 | vlan.bdg_priority)) 122 | 123 | 124 | if __name__ == '__main__': 125 | main() 126 | -------------------------------------------------------------------------------- /samples/nx-config-svi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure SVI. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch 36 | and configure SVI.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create ConfigureInterfaces to do multiple SVI configuration at a time 48 | config = NX.ConfigInterfaces() 49 | 50 | # Create SVI objects providing vlans 51 | svi1 = NX.SVI('vlan33') 52 | svi2 = NX.SVI('vlan44') 53 | 54 | # Add svis to the config 55 | config.add_svis(svi1) 56 | config.add_svis(svi2) 57 | 58 | # Push entire configuration to the switch 59 | # Note: Using svi1.get_url() and svi1.get_json() only one svi 60 | # configuration can be pushed to the switch 61 | resp = session.push_to_switch(config.get_url(), config.get_json()) 62 | if not resp.ok: 63 | print ('%% Could not login to Switch') 64 | print resp.text 65 | sys.exit(0) 66 | 67 | data = [] 68 | svis = NX.SVI.get(session) 69 | for svi in svis: 70 | data.append((svi.id, svi.admin_st, svi.bw, svi.mtu, 71 | svi.descr)) 72 | 73 | # Display the data downloaded (Uncomment below 74 | # lines to get the configured SVI) 75 | template = "{0:15} {1:15} {2:15} {3:15} {4:40}" 76 | print(template.format(" ID " , " ADMIN ", " BANDWIDTH ", 77 | " MTU ", " DESCR.")) 78 | print(template.format("---------", "-------", "-----------", 79 | "------ ", "--------")) 80 | for rec in data: 81 | print(template.format(*rec)) 82 | 83 | 84 | # Uncomment below lines to delete the created svi 85 | ''' 86 | for id in ['vlan10', 'vlan20']: 87 | resp = session.delete(svi1.get_delete_url(id)) 88 | if not resp.ok: 89 | print ('%% Could not login to Switch') 90 | print resp.text 91 | sys.exit(0) 92 | ''' 93 | 94 | 95 | if __name__ == '__main__': 96 | main() 97 | -------------------------------------------------------------------------------- /samples/nx-config-syslog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Sample of configuring logging parameters 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | def main(): 27 | """ 28 | Main execution routine 29 | 30 | :return: None 31 | """ 32 | # Take login credentials from the command line if provided 33 | # Otherwise, take them from your environment variables file ~/.profile 34 | description = '''Simple application that logs on to the Switch and 35 | configure Syslogs''' 36 | creds = NX.Credentials('switch', description) 37 | args = creds.get() 38 | 39 | # Login to Switch 40 | session = NX.Session(args.url, args.login, args.password) 41 | 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create Logging object 48 | log = NX.Logging() 49 | 50 | # Create timestamp 51 | timestamp = NX.LogTimeStamp(format='milliseconds') 52 | 53 | # Create logging console 54 | console = NX.LogConsole(admin_st='1', severity='2') 55 | 56 | # Create logging monitor 57 | monitor = NX.LogMonitor(admin_st='1', severity='2') 58 | 59 | # Create source interface logs 60 | source_iface = NX.LogSourceInterface(admin_st='1', if_name='lo 2') 61 | 62 | # Create logging level 63 | level = NX.LogLevel(severity='2', facility='local5') 64 | 65 | # Create server logs 66 | server = NX.LogServer(host='10.10.1.12', severity='2', 67 | vrf_name='management', fwd_facility='auth') 68 | 69 | # Attach or set all the log 70 | log.add_log(timestamp) 71 | log.add_log(console) 72 | log.add_log(monitor) 73 | log.add_log(source_iface) 74 | log.add_log(level) 75 | log.add_log(server) 76 | 77 | # Push entire configuration to switch 78 | resp = session.push_to_switch(log.get_url(), log.get_json()) 79 | if not resp.ok: 80 | print('%% Error: Could not push configuration to Switch') 81 | print(resp.text) 82 | 83 | if __name__ == '__main__': 84 | main() 85 | -------------------------------------------------------------------------------- /samples/nx-config-udld.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and Configure UDLD 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and Configure UDLD.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | ''' Login to Switch ''' 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | udld = NX.UDLD() # Create UDLD instance 48 | 49 | int = NX.Interface('eth1/2') 50 | 51 | udld.enable_aggress() 52 | udld.disable_aggress(int) 53 | 54 | ''' Push UDLD configuration to the switch ''' 55 | resp = session.push_to_switch(udld.get_url(), udld.get_json()) 56 | if not resp.ok: 57 | print resp.text 58 | print ('Could not push to Switch') 59 | exit(0) 60 | 61 | # Uncomment below lines to delete UDLD configuration 62 | ''' 63 | resp = session.delete(udld.get_url()) 64 | if not resp.ok: 65 | print('%% Could not delete from Switch') 66 | sys.exit(0) 67 | ''' 68 | 69 | udld_data = NX.UDLD.get(session) # Pass interface to get specific 70 | # interface details 71 | print "UDLD global configuration mode aggressive:", udld_data.aggress 72 | print "UDLD global message interval:", udld_data.g_msg_int 73 | template = "{0:12} {1:12}" 74 | print template.format("Interface", "aggress") 75 | print template.format("----------", "----------") 76 | for (id, aggress) in zip(udld_data.i_faces, udld_data.int_aggresses): 77 | print template.format(id, aggress) 78 | 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /samples/nx-config-vlan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | from nxtoolkit.nxtoolkit import ConfigInterfaces 21 | """ 22 | Simple application that logs on to the Switch and create vlan 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the 37 | Switch and create vlan.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Create L2BD objects 49 | vlan1 = NX.L2BD('vlan-112') 50 | vlan2 = NX.L2BD('vlan-223') 51 | 52 | # Create a ConfigBDs object to configure multiple l2bd at a time 53 | bds = NX.ConfigBDs() 54 | 55 | # Attach L2DB instance or created VLANS 56 | bds.add_l2bds(vlan1) 57 | bds.add_l2bds(vlan2) 58 | 59 | # Configures the switch 60 | # Note: vlan1.get_json() and vlan1.get_url() methods can be used to 61 | # configure a single vlan instead of bds.get_url(), bds.get_json() 62 | resp = session.push_to_switch(bds.get_url(), bds.get_json()) 63 | if not resp.ok: 64 | print resp.text 65 | print ('Could not create vlans') 66 | exit(0) 67 | 68 | # Create interface objects 69 | int1 = NX.Interface('eth1/15') 70 | int2 = NX.Interface('eth1/16') 71 | 72 | # Enable above created vlans on the interfaces 73 | int1.set_access_vlan('vlan-111') 74 | int2.set_access_vlan('vlan-222') 75 | 76 | #ConfigInterfaces class is used to configure multiple interfaces at a time 77 | config = ConfigInterfaces() 78 | config.add_interface(int1) 79 | config.add_interface(int2) 80 | 81 | # Push all interface configuration to the switch 82 | resp = session.push_to_switch(config.get_url(), config.get_json()) 83 | if not resp.ok: 84 | print resp.text 85 | print ('Could not create port-channel') 86 | exit(0) 87 | 88 | 89 | if __name__ == '__main__': 90 | main() 91 | -------------------------------------------------------------------------------- /samples/nx-config-vrrp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Sample of configuring VRRP parameters 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | def main(): 27 | """ 28 | Main execution routine 29 | 30 | :return: None 31 | """ 32 | # Take login credentials from the command line if provided 33 | # Otherwise, take them from your environment variables file ~/.profile 34 | description = '''Simple application that logs on to the 35 | Switch and configure VRRP''' 36 | creds = NX.Credentials('switch', description) 37 | args = creds.get() 38 | 39 | # Login to Switch 40 | session = NX.Session(args.url, args.login, args.password) 41 | 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Object to create multiple VRRP's 48 | vrrp = NX.ConfigVrrps(session) 49 | 50 | # Create interface object 51 | int1 = NX.Interface('eth1/12') 52 | 53 | # Make it L3 interface 54 | int1.set_layer('Layer3') 55 | 56 | # Push interface configuration to the switch 57 | resp = session.push_to_switch(int1.get_url(), int1.get_json()) 58 | if not resp.ok: 59 | print('%% Error: Could not push configuration to Switch') 60 | print(resp.text) 61 | 62 | # Create VRRP object for interface 63 | vrrp_int1 = NX.Vrrp(int1) 64 | 65 | #create vrrpID 66 | vrrp_id1 = NX.VrrpID('50') 67 | 68 | # Set the parameter in VrrpID 69 | vrrp_id1.set_primary('10.10.0.11') 70 | vrrp_id1.set_secondary('10.10.1.12') 71 | 72 | # Attach vrrpID to vrrp interface 73 | vrrp_int1.add_vrrp_id(vrrp_id1) 74 | 75 | # Attach the modules to VRRP object 76 | vrrp.add_vrrp(vrrp_int1) 77 | 78 | # Uncomment the below two lines to print url and json response 79 | # print vrrp.get_url() 80 | # print vrrp.get_json() 81 | 82 | # Push entire configuration to the switch 83 | resp = session.push_to_switch(vrrp.get_url(), vrrp.get_json()) 84 | if not resp.ok: 85 | print('%% Error: Could not push configuration to Switch') 86 | print(resp.text) 87 | 88 | 89 | if __name__ == '__main__': 90 | main() -------------------------------------------------------------------------------- /samples/nx-copy-running-startup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and copy the 22 | running config to startup config 23 | """ 24 | 25 | import sys 26 | import nxtoolkit.nxtoolkit as NX 27 | import time 28 | 29 | 30 | def main(): 31 | """ 32 | Main execution routine 33 | 34 | :return: None 35 | """ 36 | # Take login credentials from the command line if provided 37 | # Otherwise, take them from your environment variables file ~/.profile 38 | description = 'copy running config to startup config' 39 | creds = NX.Credentials('switch', description) 40 | args = creds.get() 41 | 42 | # Login to Switch 43 | session = NX.Session(args.url, args.login, args.password) 44 | resp = session.login() 45 | if not resp.ok: 46 | print('%% Could not login to Switch') 47 | sys.exit(0) 48 | 49 | copy = NX.Copy() 50 | run_to_start = NX.RunningToStartUp() 51 | copy.add(run_to_start) 52 | 53 | resp = session.push_to_switch(copy.get_url(), copy.get_json()) 54 | if not resp.ok: 55 | print resp.text 56 | print('%% Could not push to the switch') 57 | exit(0) 58 | 59 | # Get the status of copy 60 | time.sleep(5) # Waiting 5 sec. till the copy process is complete 61 | copy = NX.Copy.get(session) 62 | print "Copy status: ", copy.run_to_start.status 63 | 64 | # Uncomment below lines to delete the copy task 65 | ''' 66 | resp = session.delete(run_to_start.get_url()) 67 | if not resp.ok: 68 | print resp.text 69 | print('%% Could not delete from the switch') 70 | exit(0) 71 | ''' 72 | 73 | 74 | if __name__ == '__main__': 75 | main() 76 | -------------------------------------------------------------------------------- /samples/nx-create-bgp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configure BGP session. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch and 36 | configure BGP session.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | bgpSession = NX.BGPSession("20") 48 | 49 | bgpDom= NX.BGPDomain("default") 50 | bgpDom.set_router_id("10.0.0.14") 51 | 52 | bgpPeer = NX.BGPPeer("10.0.0.1", bgpDom) 53 | bgpPeer.set_remote_as("1") 54 | bgpDom.add_peer(bgpPeer) 55 | 56 | bgpPeerAf = NX.BGPPeerAF('ipv4-ucast', bgpPeer) 57 | 58 | bgpPeer = NX.BGPPeer("192.168.45.25", bgpDom) 59 | bgpPeer.set_remote_as("2") 60 | bgpPeer.add_af(bgpPeerAf) 61 | bgpDom.add_peer(bgpPeer) 62 | 63 | bgpDomAf = NX.BGPDomainAF('ipv4-ucast', bgpDom) 64 | 65 | advPrefix = NX.BGPAdvPrefix("10.0.0.11/32", bgpDomAf) 66 | bgpDomAf.add_adv_prefix(advPrefix) 67 | 68 | advPrefix = NX.BGPAdvPrefix("10.0.0.12/32", bgpDomAf) 69 | bgpDomAf.add_adv_prefix(advPrefix) 70 | 71 | advPrefix = NX.BGPAdvPrefix("10.0.0.13/32", bgpDomAf) 72 | bgpDomAf.add_adv_prefix(advPrefix) 73 | 74 | advPrefix = NX.BGPAdvPrefix("10.0.0.14/32", bgpDomAf) 75 | bgpDomAf.add_adv_prefix(advPrefix) 76 | 77 | bgpDom.add_af(bgpDomAf) 78 | bgpSession.add_domain(bgpDom) 79 | 80 | print bgpSession.get_url(bgpSession) 81 | print bgpSession.get_json() 82 | 83 | # Push the bgpSession to the Switch 84 | resp = session.push_to_switch(bgpSession.get_url(bgpSession), 85 | bgpSession.get_json()) 86 | 87 | if not resp.ok: 88 | print('%% Error: Could not push configuration to Switch') 89 | print(resp.text) 90 | 91 | if __name__ == '__main__': 92 | main() 93 | -------------------------------------------------------------------------------- /samples/nx-create-l2bds.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and configures l2bd. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch 36 | and configure l2bd.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create a ConfigBDs object to configure multiple l2bd at a time 48 | bds = NX.ConfigBDs() 49 | 50 | # Create L2BD objects 51 | l2BDs = NX.L2BD('vlan-274') 52 | 53 | # Attach L2DB instance 54 | bds.add_l2bds(l2BDs) 55 | 56 | # Push the tenant to the Switch 57 | resp = session.push_to_switch(bds.get_url(), 58 | bds.get_json()) 59 | if not resp.ok: 60 | print('%% Error: Could not push configuration to Switch') 61 | print(resp.text) 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /samples/nx-show-bgp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays BGP 22 | session information. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the Switch and 37 | displays BGP session information.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | bgpSessions = NX.BGPSession.get(session) 49 | 50 | print("BGP Instance") 51 | print("------------") 52 | 53 | for bgpSession in bgpSessions: 54 | print bgpSession.get_as_num() 55 | 56 | for bgpSession in bgpSessions: 57 | bgpDoms = NX.BGPDomain.get(session, bgpSession) 58 | 59 | for bgpDom in bgpDoms: 60 | dom_data = [] 61 | dom_template = "{0:5} {1:20} {2:15}" 62 | print(dom_template.format("", "Domain Name", "Router ID")) 63 | print(dom_template.format("", "-----------", "-------------")) 64 | 65 | print(dom_template.format("", bgpDom.get_name(), 66 | bgpDom.get_router_id())) 67 | 68 | dom_peer_data = [] 69 | dom_peer_template = "{0:5} {1:20} {2:15} {3:6}" 70 | print(dom_peer_template.format("", "", "Peer Address", "AS Num")) 71 | print(dom_peer_template.format("", "", "-------------", "------")) 72 | 73 | bgpDomPeers = NX.BGPPeer.get(session, bgpDom) 74 | for bgpDomPeer in bgpDomPeers: 75 | dom_peer_data.append(("", "", bgpDomPeer.get_addr(), 76 | bgpDomPeer.get_remote_as())) 77 | 78 | for peer_rec in dom_peer_data: 79 | print(dom_peer_template.format(*peer_rec)) 80 | 81 | bgpDomAfs = NX.BGPDomainAF.get(session, bgpDom) 82 | dom_af_data = [] 83 | dom_af_template = "{0:5} {1:20} {2:15}" 84 | print(dom_af_template.format("", "", "Address Family")) 85 | print(dom_af_template.format("", "", "-------------")) 86 | 87 | for bgpDomAf in bgpDomAfs: 88 | dom_af_data.append(("", "", bgpDomAf.get_type())) 89 | 90 | for af_rec in dom_af_data: 91 | print(dom_af_template.format(*af_rec)) 92 | 93 | 94 | if __name__ == '__main__': 95 | main() 96 | -------------------------------------------------------------------------------- /samples/nx-show-cdp-neighbors.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays the cdp neighbors. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch and 36 | displays the cdp neighbors''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | cdp_detail = NX.LinkNeighbors.get(session) 48 | data = [] 49 | if not len(cdp_detail): 50 | print "NO CDP entry found for given interface." 51 | exit() 52 | else: 53 | for cdp in cdp_detail: 54 | data.append((cdp.attributes['devId'], 55 | cdp.attributes['id'], 56 | cdp.attributes['Hldtme'], 57 | cdp.attributes['cap'], 58 | cdp.attributes['platId'], 59 | cdp.attributes['portId'])) 60 | 61 | # Display the data downloaded 62 | template = "{0:35} {1:13} {2:6} {3:40} {4:20} {5:10} " 63 | print(template.format("Device-ID", "Local Iface", "Hldtme", "Capability", 64 | "Platform", "Port ID")) 65 | print(template.format("---------", "-----------", "------", "----------", 66 | "--------", "--------",)) 67 | for rec in data: 68 | print(template.format(*rec)) 69 | 70 | if __name__ == '__main__': 71 | main() 72 | -------------------------------------------------------------------------------- /samples/nx-show-dns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays the DNS details. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and displays the DNS details.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | 48 | dns = NX.DNS.get(session) 49 | print "Dns lookup state:", dns.get_admin_st() 50 | for prof in dns.profiles: 51 | print "\nDns profile name:", prof.name 52 | for provider in prof.providers: 53 | print "\tProvider ip:", provider.address 54 | for domain in prof.domains: 55 | print "\tDomain name:", domain.name 56 | for domain_ext in prof.domain_exts: 57 | print "\tDomain list name:", domain_ext.name 58 | for host in prof.hosts: 59 | print "\tHost name:%s\t\tAddress:%s"% (host.name, host.address) 60 | for vrf in prof.vrfs: 61 | for provider in vrf.providers: 62 | print "\tVrf name:%s\tProvider ip:%s"% (vrf.name, 63 | provider.address) 64 | for domain in vrf.domains: 65 | print "\tVrf name:%s\tDomain name:%s"% (vrf.name, 66 | domain.name) 67 | for domain_ext in vrf.domain_exts: 68 | print "\tVrf name:%s\tDomain list name:%s"% (vrf.name, 69 | domain_ext.name) 70 | 71 | if __name__ == '__main__': 72 | main() -------------------------------------------------------------------------------- /samples/nx-show-fantrays.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and fan info 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch 36 | and fan info.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Download all of the interfaces 48 | # and store the data as tuples in a list 49 | data = [] 50 | fantrays = NX.Fantray.get(session) 51 | for fantray in fantrays: 52 | data.append((fantray.slot, 53 | fantray.model, 54 | fantray.name, 55 | fantray.serial, 56 | fantray.oper_st, 57 | fantray.id, 58 | fantray.direction, 59 | fantray.speed)) 60 | 61 | # Display the data downloaded 62 | template = "{0:5} {1:12} {2:^11} {3:^10} {4:9} {5:10} {6:5}" 63 | print(template.format("SLOT", "MODEL", "SERIAL NUM", "OPER STATE", 64 | "ID", "DIRECTION", "SPEED")) 65 | print(template.format("----", "------------", "-----------", "----------", 66 | "---------", "----------", "-----")) 67 | for rec in data: 68 | print(template.format(*rec)) 69 | 70 | if __name__ == '__main__': 71 | main() 72 | -------------------------------------------------------------------------------- /samples/nx-show-hardware-buffer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays the 22 | hardware buffer information. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = """Simple application that logs on to the Switch and 37 | displays the hardware buffer information.""" 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | print "\t \t Output Shared Service Pool Buffer Utilization (in cells)" 48 | 49 | template = "{0:20} {1:20} {2:20} {3:20} {4:20}" 50 | print(template.format(" Pool ", " Total_instant_usage ", 51 | " Rem_instant_usage ", " Max_cell_usage ", 52 | " Switch_cell_count ")) 53 | print(template.format("------------ ", "------------ ", "------------ ", 54 | "---------------", "---------------")) 55 | hardware = NX.Hardware.get(session) 56 | resp = hardware.internal.get() 57 | for index in range (0,4): 58 | print(template.format('SP-'+str(index), 59 | resp.buffer['total_instant'][index], 60 | resp.buffer['rem_instant'][index], 61 | resp.buffer['max_cell'][index], 62 | resp.buffer['switch_cell'][index])) 63 | 64 | 65 | if __name__ == '__main__': 66 | main() 67 | -------------------------------------------------------------------------------- /samples/nx-show-ifs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays all 22 | of the physical nodes; both belonging to and connected to the 23 | fabric. 24 | """ 25 | import sys 26 | from nxtoolkit.nxtoolkit import (Session, Credentials, 27 | Interface, ExternalSwitch) 28 | 29 | 30 | def main(): 31 | """ 32 | Main execution routine 33 | 34 | :return: None 35 | """ 36 | # Take login credentials from the command line if provided 37 | # Otherwise, take them from your environment variables file ~/.profile 38 | description = ('Simple application that logs on to the Switch and' 39 | 'displays all of the physical nodes; both belonging' 40 | ' to and connected to the fabric.') 41 | creds = Credentials('switch', description) 42 | args = creds.get() 43 | 44 | # Login to Switch 45 | session = Session(args.url, args.login, args.password) 46 | resp = session.login() 47 | if not resp.ok: 48 | print('%% Could not login to Switch') 49 | sys.exit(0) 50 | 51 | # List of classes to get and print 52 | phy_classes = (Interface, ExternalSwitch) 53 | 54 | for phy_class in phy_classes: 55 | # Print the class name 56 | class_name = phy_class.__name__ 57 | print(class_name) 58 | print('=' * len(class_name)) 59 | 60 | # Get and print all of the items from the Switch 61 | items = phy_class.get(session) 62 | for item in items: 63 | print(item.info()) 64 | 65 | if __name__ == '__main__': 66 | main() 67 | -------------------------------------------------------------------------------- /samples/nx-show-interface-stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays stats for all of 22 | the Interfaces. 23 | """ 24 | from operator import attrgetter 25 | import sys 26 | import nxtoolkit.nxtoolkit as NX 27 | 28 | 29 | def show_stats_short(args, interfaces): 30 | """ 31 | show stats short routine 32 | 33 | :param args: command line arguments 34 | :param interfaces: list of interfaces 35 | :return: None 36 | """ 37 | # setup template and display header information 38 | template = "{0:16} {1:16} {2:16} {3:16} {4:16} {5:16}" 39 | print(template.format(" INTERFACE ", "Status", "RX BYTES/Sec", 40 | "TX BYTES/Sec", "RX PKTs/Sec","TX PKTs/Sec")) 41 | print(template.format("--------------", "------------ ", "------------ ", 42 | "---------------", "---------------", 43 | "---------------")) 44 | template = "{0:16} {1:16} {2:16,.2f} {3:16,.2f} {4:16,.2f} {5:16,.2f}" 45 | 46 | for interface in sorted(interfaces, key=attrgetter('if_name')): 47 | interface.stats.get() 48 | 49 | rec = [] 50 | allzero = True 51 | for (counter_family, count_name) in [('rmonIfIn', 'octetRate'), 52 | ('rmonIfOut', 'octetRate'), 53 | ('rmonIfIn', 'packetRate'), 54 | ('rmonIfOut', 'packetRate')]: 55 | rec.append(interface.stats.retrieve(counter_family, count_name)) 56 | 57 | if interface.stats.retrieve(counter_family, count_name) != 0: 58 | allzero = False 59 | if (args.nonzero and not allzero) or not args.nonzero: 60 | print(template.format(interface.name, interface.operSt, *rec)) 61 | 62 | 63 | def show_stats_long(args, interfaces): 64 | """ 65 | show stats long routine 66 | 67 | :param args: command line arguments 68 | :param interfaces: list of interfaces 69 | :return: None 70 | """ 71 | print('Interface {0}/{1}'.format(interfaces[0].module,interfaces[0].port)) 72 | stats = interfaces[0].stats.get() 73 | for stats_family in sorted(stats): 74 | print stats_family 75 | for counter in sorted(stats[stats_family]): 76 | print(' {0:>25}: {1}'.format(counter, 77 | stats[stats_family][counter])) 78 | 79 | 80 | def main(): 81 | """ 82 | Main execution routine 83 | 84 | :return: None 85 | """ 86 | # Take login credentials from the command line if provided 87 | # Otherwise, take them from your environment variables file ~/.profile 88 | description = '''Simple application that logs on to the Switch and 89 | displays stats for all of the Interfaces.''' 90 | creds = NX.Credentials('switch', description) 91 | creds.add_argument('-i', '--interface', 92 | type=str, 93 | help='Specify a particular interface module/port e.g. 1/21') 94 | creds.add_argument('-f', '--full', action="store_true", 95 | help='''Show full statistics - only available 96 | if interface is specified''') 97 | creds.add_argument('-n', '--nonzero', action='store_true', 98 | help='''Show only interfaces where the counters are not zero. 99 | - only available if interface is NOT specified''') 100 | args = creds.get() 101 | 102 | # Login to switch 103 | session = NX.Session(args.url, args.login, args.password) 104 | resp = session.login() 105 | if not resp.ok: 106 | print('%% Could not login to Switch') 107 | sys.exit(0) 108 | 109 | # Download all of the interfaces and get their stats 110 | # and display the stats 111 | if args.interface: 112 | interface = args.interface 113 | if 'eth ' in interface: 114 | interface = interface[4:] 115 | #(module, port) = interface.split('/') 116 | 117 | #interfaces = NX.Interface.get(session, module, port) 118 | interfaces = NX.Interface.get(session, 'eth'+interface) 119 | else: 120 | interfaces = NX.Interface.get(session) 121 | 122 | if not args.full or not args.interface: 123 | show_stats_short(args, interfaces) 124 | else: 125 | show_stats_long(args, interfaces) 126 | 127 | if __name__ == '__main__': 128 | try: 129 | main() 130 | except KeyboardInterrupt: 131 | pass 132 | -------------------------------------------------------------------------------- /samples/nx-show-interfaces.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays all 22 | of the Interfaces. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the Switch and 37 | displays all of the Interfaces.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Download all of the interfaces 49 | # and store the data as tuples in a list 50 | data = [] 51 | interfaces = NX.Interface.get(session) 52 | for interface in interfaces: 53 | data.append((interface.attributes['if_name'], 54 | interface.attributes['porttype'], 55 | interface.attributes['adminstatus'], 56 | interface.attributes['operSt'], 57 | interface.attributes['speed'], 58 | interface.attributes['mtu'], 59 | interface.attributes['usage'])) 60 | 61 | # Display the data downloaded 62 | template = "{0:17} {1:6} {2:^6} {3:^6} {4:7} {5:6} {6:9}" 63 | print(template.format("INTERFACE", "TYPE", "ADMIN", "OPER", 64 | "SPEED", "MTU", "USAGE")) 65 | print(template.format("---------", "----", "------", "------", 66 | "-----", "---", "---------")) 67 | for rec in data: 68 | print(template.format(*rec)) 69 | 70 | 71 | if __name__ == '__main__': 72 | main() 73 | -------------------------------------------------------------------------------- /samples/nx-show-ip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and get ipv6 details. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and get ipv6 details.''' 37 | creds = NX.Credentials('switch', description) 38 | 39 | creds.add_argument('-v', '--version', type=str, default='v4', 40 | help='''IP version (Example: v4, v6), By default its v4''') 41 | 42 | args = creds.get() 43 | 44 | # Login to Switch 45 | session = NX.Session(args.url, args.login, args.password) 46 | resp = session.login() 47 | if not resp.ok: 48 | print('%% Could not login to Switch') 49 | sys.exit(0) 50 | 51 | # Get IP infos. from the switch(default version is v4) 52 | ipv = NX.IP.get(session, args.version) 53 | 54 | # Display ip interface details 55 | template = "{0:15} {1:15} {2:32}" 56 | print(template.format(" Interface ", " Admin status ", 57 | " IP%s addresses %s" % (args.version, 58 | ('/ Link-local address' if 'v6' in args.version else '')))) 59 | print(template.format("-----------", "--------------", 60 | "------------------------------------")) 61 | for iface in ipv.interfaces: 62 | print(template.format(iface.get_if_name(), iface.get_admin_st(), 63 | iface.get_address())) 64 | 65 | # Display ip route details 66 | template = "{0:20} {1:15} {2:15} {3:15} {4:15}" 67 | for route in ipv.routes: 68 | print "\nRoute prefix : %s" % (route.prefix) 69 | for n_hop in route.next_hops: 70 | print(template.format("\tNext Hop Addr ", " Interface ", 71 | " Vrf ", " Tag ", " Track Id")) 72 | print(template.format("\t--------------", "--------------", 73 | "------", "-----", "---------")) 74 | print(template.format("\t"+n_hop.addr, n_hop.i_face, n_hop.vrf, 75 | n_hop.tag, n_hop.track_id)) 76 | 77 | 78 | if __name__ == '__main__': 79 | main() -------------------------------------------------------------------------------- /samples/nx-show-l2bds.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays all 22 | of the l2bd's. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the Switch 37 | and displays all of the l2bd's.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Download all of the interfaces 49 | # and store the data as tuples in a list 50 | data = [] 51 | l2BDs = NX.L2BD.get(session) 52 | for l2BD in l2BDs: 53 | data.append((l2BD.id, 54 | l2BD.bridgeMode, 55 | l2BD.adminSt, 56 | l2BD.operSt, 57 | l2BD.unkMacUcastAct, 58 | l2BD.unkMcastAct)) 59 | 60 | data = sorted(data) 61 | 62 | # Display the data downloaded 63 | template = "{0:5} {1:12} {2:^11} {3:^10} {4:9} {5:8}" 64 | print(template.format("ID", "Bridge Mode", "ADMIN STATE", "OPER STATE", 65 | "UNK UCAST", "UNK MCAST")) 66 | print(template.format("----", "------------", "-----------", "----------", 67 | "---------", "--------")) 68 | for rec in data: 69 | print(template.format(*rec)) 70 | 71 | 72 | if __name__ == '__main__': 73 | main() 74 | -------------------------------------------------------------------------------- /samples/nx-show-linecards.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays linecards details. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch and 36 | displays linecards details.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Download all of the interfaces 48 | # and store the data as tuples in a list 49 | data = [] 50 | LCs = NX.Linecard.get(session) 51 | for LC in LCs: 52 | data.append((LC.slot, 53 | LC.model, 54 | LC.serial, 55 | LC.oper_st, 56 | LC.num_ports, 57 | LC.firmware, 58 | LC.bios, 59 | LC.hardware_version, 60 | LC.hardware_revision)) 61 | 62 | # Display the data downloaded 63 | template = "{0:5} {1:12} {2:^11} {3:^10} {4:9} {5:8} {6:6} {7:6} {8:6}" 64 | print(template.format("SLOT", "MODEL", "SERIAL NUM", "OPER STATE", 65 | "NUM PORTS", "FIRMWARE", "BIOS", "HW VER", "HW REV")) 66 | print(template.format("----", "------------", "-----------", "----------", 67 | "---------", "--------", "----", "------", "-----")) 68 | for rec in data: 69 | print(template.format(*rec)) 70 | 71 | 72 | if __name__ == '__main__': 73 | main() 74 | -------------------------------------------------------------------------------- /samples/nx-show-port-channel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and show port channels 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | import time 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the Switch 36 | and show port channels''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | pc_list = [] 48 | port_channels = NX.PortChannel.get(session) 49 | template = "{0:16} {1:15} {2:16} {3:16} {4:16}" 50 | print(template.format(" Group ", " Port channel ", " Layer ", 51 | "Port channel Mode", " Members ")) 52 | print(template.format("---------", " ------------ ", " ----- ", 53 | "-----------------", " --------")) 54 | for pc in port_channels: 55 | pc_list.append((pc.pc_id, pc.name, pc.layer, pc.pc_mode, 56 | [str(iface.if_name) for iface in pc._interfaces])) 57 | 58 | # Display all the downloaded data 59 | for rec in pc_list: 60 | print(template.format(*rec)) 61 | 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /samples/nx-show-process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that shows all of the processes running on a switch 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | #import nxtoolkit.nxphysobject as NX_PHYS 26 | from nxtoolkit.nxtoolkitlib import Credentials 27 | 28 | 29 | def main(): 30 | """ 31 | Main show Process routine 32 | :return: None 33 | """ 34 | description = '''Simple application that logs on to the Switch and 35 | displays process information for a switch''' 36 | creds = Credentials('switch', description) 37 | args = creds.get() 38 | 39 | session = NX.Session(args.url, args.login, args.password) 40 | resp = session.login() 41 | if not resp.ok: 42 | print '%% Could not login to Switch' 43 | sys.exit(0) 44 | 45 | switch = NX.Node.get(session) 46 | processes = NX.Process.get(session, switch) 47 | tables = NX.Process.get_table(processes, 'Process list for Switch ::') 48 | for table in tables: 49 | print table.get_text(tablefmt='fancy_grid') + '\n' 50 | 51 | 52 | if __name__ == '__main__': 53 | try: 54 | main() 55 | except KeyboardInterrupt: 56 | pass 57 | -------------------------------------------------------------------------------- /samples/nx-show-psus.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays Power 22 | supply information. 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = """Simple application that logs on to the Switch and displays 37 | Power supply information.""" 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Download all of the interfaces 49 | # and store the data as tuples in a list 50 | data = [] 51 | psus = NX.Powersupply.get(session) 52 | for psu in psus: 53 | data.append((pwr_sup.slot, 54 | pwr_sup.model, 55 | pwr_sup.serial, 56 | pwr_sup.oper_st, 57 | pwr_sup.voltage_source, 58 | pwr_sup.fan_status, 59 | pwr_sup.hardware_version, 60 | pwr_sup.hardware_revision)) 61 | 62 | # Display the data downloaded 63 | template = "{0:5} {1:12} {2:^11} {3:^10} {4:9} {5:6} {6:6}" 64 | print(template.format("SLOT", "MODEL", "SERIAL NUM", "OPER STATE", 65 | "VOLT SRC", "HW VER", "HW REV")) 66 | print(template.format("----", "------------", "-----------", "----------", 67 | "---------", "------", "------")) 68 | for rec in data: 69 | print(template.format(*rec)) 70 | 71 | if __name__ == '__main__': 72 | main() 73 | -------------------------------------------------------------------------------- /samples/nx-show-rbac.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays RBAC details. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and displays RBAC details.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | rbac = NX.RBAC.get(session) 48 | print "Password Max Length:", rbac.pwd_max_len 49 | print "Password Min Length:", rbac.pwd_min_len 50 | print "Password Secure Mode Enabled:", rbac.pwd_secure_mode 51 | print "Password Strength Check Enabled:", rbac.pwd_strength_check 52 | 53 | print "List of roles:" 54 | print "===============" 55 | for role in rbac.roles: 56 | print role 57 | 58 | # Uncomment the below lines to get specific role 59 | ''' 60 | rbac = NX.RBAC.get(session, role_name='test-role') 61 | for role in rbac.roles: 62 | print role 63 | ''' 64 | 65 | print "List of users and user details:" 66 | print "===============================" 67 | for user in rbac.users: 68 | print "User:", user.name 69 | print "Roles:" 70 | for role in user.user_roles: print role 71 | print "Ssh key:", user.ssh_key 72 | 73 | # Uncomment below lines to get specific user details 74 | ''' 75 | print "User Details" 76 | print "=============" 77 | user = NX.AaaUser.get(session, 'test1') 78 | print "User:", user.name 79 | print "Roles:" 80 | for role in user.user_roles: print role 81 | print "Ssh key:", user.ssh_key 82 | ''' 83 | 84 | print "Radius Server Details" 85 | print "=========================" 86 | rad = NX.AaaRadius.get(session) 87 | print "timeout value:", rad.timeout 88 | print "retransmission count:", rad.retries 89 | print "source interface:", rad.src_int 90 | 91 | print "total number of servers:", len(rad.servers) 92 | print "following RADIUS servers are configured:" 93 | for provider in rad.servers: 94 | print provider.name 95 | print "\ttimeout:", provider.timeout 96 | print "\tretries:", provider.retries 97 | 98 | # To get specific host details from Radius server 99 | ''' 100 | rad = NX.AaaRadius.get(session, host_name='1.2.3.4') 101 | for provider in rad.servers: 102 | print provider.name 103 | print "\ttimeout:", provider.timeout 104 | print "\tretries:", provider.retries 105 | ''' 106 | 107 | print "Tacacs+ Server Details" 108 | print "=========================" 109 | tac = NX.AaaTacacs.get(session) 110 | print "timeout value:", tac.timeout 111 | print "deadtime value:", tac.deadtime 112 | print "source interface:", tac.src_int 113 | 114 | print "total number of servers:", len(tac.servers) 115 | print "following TACACS+ servers are configured:" 116 | for provider in tac.servers: 117 | print provider.name 118 | print "\tavailable on port:", provider.port 119 | print "\ttimeout:", provider.timeout 120 | 121 | print "total number of groups:",len(tac.groups) 122 | print "following TACACS+ server groups are configured:" 123 | for group in tac.groups: 124 | print "group name:", group.name 125 | print "\tdeadtime is ", group.deadtime 126 | print "\tvrf is ", group.vrf 127 | for servers in group.grp_servers: 128 | print "\t\tserver", servers.server 129 | 130 | # To get specific host details from Tacacs+ server 131 | ''' 132 | tac_host = NX.AaaTacacs.get(session, host_name='1.2.3.4') 133 | for provider in tac_host.servers: 134 | print provider.name 135 | print "\tavailable on port:", provider.port 136 | print "\ttimeout:", provider.timeout 137 | ''' 138 | 139 | # To get specific group details from Tacacs+ server 140 | ''' 141 | tac_grp = NX.AaaTacacs.get(session, grp_name='tac1') 142 | for group in tac_grp.groups: 143 | print "group name:", group.name 144 | print "\tdeadtime is ", group.deadtime 145 | print "\tvrf is ", group.vrf 146 | for servers in group.grp_servers: 147 | print "\t\tserver", servers.server 148 | ''' 149 | 150 | print "AAA Details" 151 | print "=============" 152 | aaa = NX.AaaAaa.get(session) 153 | print ("Authentication Details") 154 | print ("Default provider group:%s\tProtocol:%s\tError-enabled:%s" % 155 | (aaa.auth_prov_grp, aaa.auth_protocol, aaa.errEn)) 156 | print ("Authorization Details") 157 | print ("Default provider group:%s\tCommand type:%s" % 158 | (aaa.author_prov_grp, aaa.cmd_type)) 159 | print ("Accounting Details") 160 | print ("Default provider group:%s" % aaa.acc_prov_grp) 161 | 162 | 163 | if __name__ == '__main__': 164 | main() -------------------------------------------------------------------------------- /samples/nx-show-rpm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays RPM details. 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = '''Simple application that logs on to the 36 | Switch and displays RPM details.''' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | 48 | print "Specific Route-map details:" 49 | print "============================" 50 | rt_map = NX.RouteMap.get(session, 'Test_route_map') 51 | print "Name:", rt_map.name 52 | for entry in rt_map.rt_map_entries: 53 | print ("Action:%s\tSequence number:%s" % (entry.action, entry.seq_no)) 54 | print "Description: ", entry.descr 55 | print "Match Clauses:" 56 | for as_path in entry.as_paths: 57 | for name in as_path.matches: 58 | print "\tas-path (as-path filter): ", name.rs_name 59 | 60 | for prefix in entry.v4_prefix_list: 61 | for name in prefix.matches: 62 | print "\tip address prefix-lists: ", name.rs_name 63 | 64 | for prefix in entry.v6_prefix_list: 65 | for name in prefix.matches: 66 | print "\tipv6 address prefix-lists: ", name.rs_name 67 | 68 | for rt_tags in entry.rt_tags: 69 | print "\ttag: ", rt_tags.tag 70 | 71 | for comm in entry.community: 72 | for name in comm.matches: 73 | print "\tcommunity (community-list filter): ", name.rs_name 74 | 75 | for rt_type in entry.rt_types: 76 | print "\troute-type: ", rt_type.type 77 | 78 | print "Set Clauses:" 79 | for hop in entry.next_hops: 80 | print "\tip next-hop ", hop.addr 81 | for pref in entry.local_preferences: 82 | print "\tlocal-preference ", pref.local_pref 83 | for origin in entry.origin: 84 | print "\torigin ", origin.origin 85 | for community in entry.comm_list: 86 | print "\tcomm-list ", community.comm_name 87 | 88 | 89 | print "Specific IP Prefix-list details:" 90 | print "============================" 91 | pfx = NX.PrefixList.get(session, 'test_prefix') 92 | print "Name:", pfx.name 93 | for prefix in pfx.prefix_list: 94 | print ("Prefix Address:%s\tAction:%s\tSequence number:%s" % 95 | (prefix.pfx_addr, prefix.action, prefix.seq_no)) 96 | 97 | print "Specific IPV6 Prefix-list details:" 98 | print "============================" 99 | pfx = NX.PrefixList.get(session, 'test_prefix', 'v6') 100 | print "Name:", pfx.name 101 | for prefix in pfx.prefix_list: 102 | print ("Prefix Address:%s\tAction:%s\tSequence number:%s" % 103 | (prefix.pfx_addr, prefix.action, prefix.seq_no)) 104 | 105 | 106 | print "Specific AS-Path Access-list details:" 107 | print "=====================================" 108 | as_path = NX.AsPath.get(session, 'testAccList') 109 | print "Name:", as_path.name 110 | for access in as_path.access_lists: 111 | print ("Action:%s\tRegex:%s\tSequence number:%s" % (access.action, 112 | access.regex, access.seq_no)) 113 | 114 | 115 | print "Specific Community-list details:" 116 | print "=================================" 117 | comm_list = NX.CommunityList.get(session, 'comrule') 118 | print "Name", comm_list.name 119 | for entry in comm_list.comm_entries: 120 | print "Action:%s\tSequence number:%s" % (entry.action, entry.seq_no) 121 | for item in entry.comm_items: 122 | print item.community 123 | 124 | 125 | if __name__ == '__main__': 126 | main() -------------------------------------------------------------------------------- /samples/nx-show-supervisors.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Simple application that logs on to the Switch and displays 22 | supervisor information 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | 28 | def main(): 29 | """ 30 | Main execution routine 31 | 32 | :return: None 33 | """ 34 | # Take login credentials from the command line if provided 35 | # Otherwise, take them from your environment variables file ~/.profile 36 | description = '''Simple application that logs on to the Switch and 37 | supervisor information.''' 38 | creds = NX.Credentials('switch', description) 39 | args = creds.get() 40 | 41 | # Login to Switch 42 | session = NX.Session(args.url, args.login, args.password) 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | # Download all of the interfaces 49 | # and store the data as tuples in a list 50 | data = [] 51 | sups = NX.Supervisorcard.get(session) 52 | for sup in sups: 53 | data.append((sup.slot, 54 | sup.model, 55 | sup.serial, 56 | sup.oper_st, 57 | sup.num_ports, 58 | sup.firmware, 59 | sup.bios, 60 | sup.hardware_version, 61 | sup.hardware_revision)) 62 | 63 | # Display the data downloaded 64 | template = "{0:5} {1:12} {2:^11} {3:^10} {4:9} {5:8} {6:6} {7:6} {8:6}" 65 | print(template.format("SLOT", "MODEL", "SERIAL NUM", "OPER STATE", 66 | "NUM PORTS", "FIRMWARE", "BIOS", "HW VER", "HW REV")) 67 | print(template.format("----", "------------", "-----------", "----------", 68 | "---------", "--------", "----", "------", "-----")) 69 | for rec in data: 70 | print(template.format(*rec)) 71 | 72 | if __name__ == '__main__': 73 | main() 74 | -------------------------------------------------------------------------------- /samples/nx-show-syslog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | """ 21 | Sample of displaying the logging parameters 22 | """ 23 | import sys 24 | import nxtoolkit.nxtoolkit as NX 25 | 26 | def main(): 27 | """ 28 | Main execution routine 29 | 30 | :return: None 31 | """ 32 | # Take login credentials from the command line if provided 33 | # Otherwise, take them from your environment variables file ~/.profile 34 | description = 'Simple application that logs on to the Switch and\ 35 | display the Syslogs parameters' 36 | creds = NX.Credentials('switch', description) 37 | args = creds.get() 38 | 39 | # Login to Switch 40 | session = NX.Session(args.url, args.login, args.password) 41 | 42 | resp = session.login() 43 | if not resp.ok: 44 | print('%% Could not login to Switch') 45 | sys.exit(0) 46 | 47 | # Create logging object (Note: Currently one string has to be passed as 48 | # parameter while creating Logging object) 49 | log = NX.Logging.get(session) 50 | 51 | timestamp = log.timestamp.get() 52 | if timestamp: 53 | data = [] 54 | data.append((timestamp.format, "")) 55 | print "TimeStamp :\n===========" 56 | template = "{0:17}" 57 | print(template.format("Format ")) 58 | print(template.format("-----------")) 59 | for rec in data: 60 | print(template.format(*rec)) 61 | print "" 62 | 63 | monitor = log.monitor.get() 64 | if monitor: 65 | data = [] 66 | data.append((monitor.admin_st, monitor.severity)) 67 | print "Monitor :\n===========" 68 | template = "{0:17} {1:17}" 69 | print(template.format("adminState ", " severity ")) 70 | print(template.format("---------------", " ----------")) 71 | for rec in data: 72 | print(template.format(*rec)) 73 | print "" 74 | 75 | console = log.console.get() 76 | if console: 77 | data = [] 78 | data.append((console.admin_st, console.severity)) 79 | print "Console :\n===========" 80 | template = "{0:17} {1:17}" 81 | print(template.format("adminState ", " severity ")) 82 | print(template.format("---------------", " ----------")) 83 | for rec in data: 84 | print(template.format(*rec)) 85 | print "" 86 | 87 | server = log.server.get() 88 | if server: 89 | data = [] 90 | data.append((server.host, monitor.severity, server.fwd_facility, 91 | server.vrf_name)) 92 | print "Server :\n===========" 93 | template = "{0:17} {1:17} {2:16} {3:16}" 94 | print(template.format("host ", " severity ", 95 | " fwd-facility", "vrf-name")) 96 | print(template.format("------------------", " ----------", 97 | " ------------", "--------")) 98 | for rec in data: 99 | print(template.format(*rec)) 100 | print "" 101 | 102 | level = log.level.get() 103 | if level: 104 | data = [] 105 | data.append((level.severity, level.facility)) 106 | print "Level :\n===========" 107 | template = "{0:17} {1:17}" 108 | print(template.format("Severity ", " Facility ")) 109 | print(template.format("---------------", " ----------")) 110 | for rec in data: 111 | print(template.format(*rec)) 112 | print "" 113 | 114 | interface = log.src_iface.get() 115 | if interface: 116 | data = [] 117 | data.append((interface.admin_st, interface.if_name)) 118 | print "Source Interface :\n==============" 119 | template = "{0:17} {1:17}" 120 | print(template.format("adminState ", " interface-name ")) 121 | print(template.format("---------------", " ----------------")) 122 | for rec in data: 123 | print(template.format(*rec)) 124 | print "" 125 | 126 | 127 | if __name__ == '__main__': 128 | main() 129 | -------------------------------------------------------------------------------- /samples/nx-show-vrrp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ################################################################################ 3 | # # 4 | # Copyright (c) 2015 Cisco Systems # 5 | # All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 8 | # not use this file except in compliance with the License. You may obtain # 9 | # a copy of the License at # 10 | # # 11 | # http://www.apache.org/licenses/LICENSE-2.0 # 12 | # # 13 | # Unless required by applicable law or agreed to in writing, software # 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 16 | # License for the specific language governing permissions and limitations # 17 | # under the License. # 18 | # # 19 | ################################################################################ 20 | from nxtoolkit.nxtoolkit import Vrrp 21 | """ 22 | Sample of displays the vrrp information 23 | """ 24 | import sys 25 | import nxtoolkit.nxtoolkit as NX 26 | 27 | def main(): 28 | """ 29 | Main execution routine 30 | 31 | :return: None 32 | """ 33 | # Take login credentials from the command line if provided 34 | # Otherwise, take them from your environment variables file ~/.profile 35 | description = 'Simple application that logs on to the Switch and\ 36 | displays vrrp information' 37 | creds = NX.Credentials('switch', description) 38 | args = creds.get() 39 | 40 | # Login to Switch 41 | session = NX.Session(args.url, args.login, args.password) 42 | 43 | resp = session.login() 44 | if not resp.ok: 45 | print('%% Could not login to Switch') 46 | sys.exit(0) 47 | 48 | template = "{0:16} {1:16} {2:16} {3:16} {4:16}" 49 | print(template.format("Interface", "VRRP ID", "priority", "Primary ip", 50 | "secondary ip")) 51 | print(template.format("------------", "------------", "------------", 52 | "------------", "------------")) 53 | 54 | # To get details of vrrp of all the interfaces 55 | for vrrp in NX.Vrrp.get(session): 56 | for id in vrrp.vrrp_ids: 57 | print(template.format(vrrp.interface, id.vrrp_id, id.get_priority(), 58 | id.get_primary(), id.get_secondary())) 59 | 60 | 61 | if __name__ == '__main__': 62 | main() -------------------------------------------------------------------------------- /scripts/install_dependencies: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script is used to self initialize the preinstalled nxtoolkit VM 4 | 5 | apt-get -y update 6 | apt-get -y upgrade 7 | cd nxtoolkit 8 | git pull 9 | python setup.py develop 10 | /etc/init.d/mysql start 11 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | NXToolkit Installer using setuptools 3 | """ 4 | import os 5 | from setuptools import setup 6 | 7 | 8 | base_dir = os.path.dirname(__file__) 9 | 10 | about = {} 11 | with open(os.path.join(base_dir, "nxtoolkit", "__about__.py")) as f: 12 | exec(f.read(), about) 13 | 14 | setup( 15 | name=about["__title__"], 16 | version=about["__version__"], 17 | packages=["nxtoolkit"], 18 | author=about["__author__"], 19 | author_email=about["__email__"], 20 | url=about["__uri__"], 21 | license=about["__license__"], 22 | install_requires=["requests", 23 | "websocket-client", 24 | "gitpython", 25 | "flask-sqlalchemy", 26 | "flask-admin", 27 | "flask-bootstrap", 28 | "flask-wtf", 29 | "flask", 30 | "pymysql", 31 | "tabulate"], 32 | description="This library allows basic Cisco Nexus configuration.", 33 | ) 34 | -------------------------------------------------------------------------------- /shippable.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "pypy" 5 | cache: true 6 | 7 | before_install: 8 | - mkdir -p shippable/codecoverage 9 | 10 | install: 11 | - "pip install requests" 12 | - "pip install coverage" 13 | - "python setup.py -q develop" 14 | 15 | script: 16 | - coverage run -p tests/nxtoolkit_test.py 17 | - coverage run -p tests/nxphysobject_test.py 18 | - coverage run -p tests/nxtoolkitlib_test.py 19 | 20 | after_success: 21 | - coverage combine 22 | - coverage report --include=*nxtoolkit* 23 | - coverage xml -o shippable/codecoverage/coverage.xml --include=*nxtoolkit* 24 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | Toolkit Unit Tests 2 | ================== 3 | 4 | The nxtoolkit package has a unit test suite that strives for a 5 | minimum of 100% code coverage. The main test suite is contained 6 | within the ``nxtoolkit_test.py`` file. Within the test suite, the 7 | tests can be classified into 2 types; live tests and offline tests. 8 | Live tests are those that actually communicate with a switch and push 9 | configuration to/from the Switch. Offline tests run locally and do not 10 | communicate with the Switch in any way. 11 | 12 | The tests are can be run in the following ways:: 13 | 14 | python nxtoolkit_test.py [offline | live | full ] 15 | 16 | The optional keyword allows ``offline``, ``live``, or the ``full`` 17 | testsuite to be run. If the keyword is not provided, the default of 18 | ``offline`` will be used. 19 | 20 | When adding additional code or making changes to the toolkit, please 21 | ensure that unit tests are added to cover the new functionality and 22 | that the entire test suite is run against the modified toolkit before 23 | submitting the code. Minimal code coverage can be verified using 24 | tools such as 25 | [coverage.py](https://pypi.python.org/pypi/coverage). For instance, 26 | after installing coverage.py, the toolkit can be run with the 27 | command:: 28 | 29 | coverage run nxtoolkit_test.py 30 | 31 | and an HTML report of the code coverage can be generated with the 32 | command:: 33 | 34 | coverage html 35 | 36 | If changes are made to the ``nxtoolkit.py`` file, please ensure that 37 | the ``nxtoolkit_test.py`` is run and that code coverage remains at 38 | 100%. 39 | 40 | -------------------------------------------------------------------------------- /tests/nxtoolkitlib_test.py: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # # 3 | # Copyright (c) 2015 Cisco Systems # 4 | # All Rights Reserved. # 5 | # # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # 7 | # not use this file except in compliance with the License. You may obtain # 8 | # a copy of the License at # 9 | # # 10 | # http://www.apache.org/licenses/LICENSE-2.0 # 11 | # # 12 | # Unless required by applicable law or agreed to in writing, software # 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # 15 | # License for the specific language governing permissions and limitations # 16 | # under the License. # 17 | # # 18 | ################################################################################ 19 | """nxtoolkitlib.py Test module 20 | """ 21 | from nxtoolkit.nxtoolkitlib import Credentials 22 | import unittest 23 | 24 | 25 | class TestCredentials(unittest.TestCase): 26 | """ 27 | Test Credentials class from nxtoolkitlib.py 28 | """ 29 | def test_create_all(self): 30 | """ 31 | Basic test for all Credentials qualifiers 32 | """ 33 | creds = Credentials(['apic', 'mysql']) 34 | 35 | def return_empty_string(disp): 36 | """ Return an empty string """ 37 | return '' 38 | 39 | creds._get_from_user = return_empty_string 40 | creds._get_password = return_empty_string 41 | self.assertTrue(isinstance(creds, Credentials)) 42 | creds.get() 43 | creds.verify() 44 | 45 | def test_create_apic_string_only(self): 46 | """ 47 | Basic test for only Switch Credentials qualifiers 48 | passed as a single string 49 | """ 50 | creds = Credentials('apic') 51 | self.assertTrue(isinstance(creds, Credentials)) 52 | 53 | def test_create_apic_list_only(self): 54 | """ 55 | Basic test for only Switch Credentials qualifiers 56 | passed as a single string in a list 57 | """ 58 | creds = Credentials(['apic']) 59 | self.assertTrue(isinstance(creds, Credentials)) 60 | 61 | if __name__ == '__main__': 62 | 63 | offline = unittest.TestSuite() 64 | offline.addTest(unittest.makeSuite(TestCredentials)) 65 | 66 | unittest.main() 67 | --------------------------------------------------------------------------------