Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.26 KB | None | 0 0
  1. """This script configures GigabitEthernet2 interfaces on network devices.
  2. Copyright (c) 2018 Cisco and/or its affiliates.
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in all
  10. copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. """
  19.  
  20.  
  21. from ncclient import manager
  22. import xmltodict
  23.  
  24.  
  25. def check_ip(device):
  26.     """This function checks the IP configuration of GigabitEthernet2
  27.    """
  28.     # MISSION TODO 1: Provide the proper type of NETCONF object needed
  29.     # Create an XML filter for targeted NETCONF queries
  30.     netconf_filter = """
  31.    <filter>
  32.      <interfaces xmlns="http://openconfig.net/yang/interfaces">
  33.        <interface>
  34.            <name>GigabitEthernet2</name>
  35.        </interface>
  36.      </interfaces>
  37.    </filter>"""
  38.     # END MISSION SECTION
  39.  
  40.     # print("Opening NETCONF Connection to {}".format(device["conn"]["host"]))
  41.  
  42.     # Open a connection to the network device using ncclient
  43.     with manager.connect(
  44.         host=device["conn"]["host"],
  45.         port=device["conn"]["netconf_port"],
  46.         username=device["conn"]["username"],
  47.         password=device["conn"]["password"],
  48.         hostkey_verify=False,
  49.     ) as m:
  50.  
  51.         # MISSION TODO 2: Provide the appropriate Manager Method Name
  52.         # print("Sending a <get-config> operation to the device.\n")
  53.         # Make a NETCONF <get-config> query using the filter
  54.         netconf_reply = m.get_config(source="running", filter=netconf_filter)
  55.     # END MISSION SECTION
  56.  
  57.     # Uncomment the below lines to print the raw XML body
  58.     # print("Here is the raw XML data returned from the device.\n")
  59.     # print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml())
  60.     # print("")
  61.  
  62.     # Parse the returned XML to an Ordered Dictionary
  63.     netconf_data = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"]
  64.  
  65.     # Get the Interface Details
  66.     interface = netconf_data["interfaces"]["interface"]
  67.  
  68.     print("Device: {}".format(device["conn"]["host"]))
  69.     print("  Interface: {}".format(interface["config"]["name"]))
  70.     try:
  71.         ipv4 = interface["subinterfaces"]["subinterface"]["ipv4"]["addresses"][
  72.             "address"
  73.         ]
  74.         print(
  75.             "    IPv4: {}/{}".format(
  76.                 ipv4["ip"], ipv4["config"]["prefix-length"]
  77.             )
  78.         )
  79.         return (
  80.             device["conn"]["host"], ipv4["ip"], ipv4["config"]["prefix-length"]
  81.         )
  82.  
  83.     except KeyError:
  84.         print("    IPv4: not configured.")
  85.     print("\n")
  86.  
  87.  
  88. def set_ip(device):
  89.     """This function configures the IP of GigabitEthernet2
  90.    """
  91.     # MISSION TODO 3: What XML attribute is used to indicate the capability?
  92.     # Create an XML configuration template for openconfig-interfaces
  93.     netconf_interface_template = """
  94.    <config>
  95.        <interfaces xmlns="http://openconfig.net/yang/interfaces">
  96.            <interface>
  97.                <name>{name}</name>
  98.                <config>
  99.                    <type
  100.                     xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">
  101.                        ianaift:ethernetCsmacd
  102.                    </type>
  103.                    <name>{name}</name>
  104.                    <enabled>{status}</enabled>
  105.                </config>
  106.                <subinterfaces>
  107.                    <subinterface>
  108.                        <index>0</index>
  109.                        <ipv4 xmlns="http://openconfig.net/yang/interfaces/ip">
  110.                            <addresses>
  111.                                <address>
  112.                                    <ip>{ip_address}</ip>
  113.                                    <config>
  114.                                        <ip>{ip_address}</ip>
  115.                                        <prefix-length>{prefix}</prefix-length>
  116.                                    </config>
  117.                                </address>
  118.                            </addresses>
  119.                        </ipv4>
  120.                        <ipv6 xmlns="http://openconfig.net/yang/interfaces/ip">
  121.                            <config>
  122.                                <enabled>false</enabled>
  123.                            </config>
  124.                        </ipv6>
  125.                    </subinterface>
  126.                </subinterfaces>
  127.            </interface>
  128.        </interfaces>
  129.    </config>"""
  130.     # END MISSION SECTION
  131.  
  132.     # Create NETCONF Payload for device
  133.     # MISSION TODO 4: What String method is used to fill in a template?
  134.     netconf_data = netconf_interface_template.format(
  135.         name="GigabitEthernet2",
  136.         status="true",
  137.         ip_address=device["ip"],
  138.         prefix=device["prefix"],
  139.     )
  140.     # END MISSION SECTION
  141.  
  142.     # Uncomment the below lines to view the config payload
  143.     # print("The configuration payload to be sent over NETCONF.\n")
  144.     # print(netconf_data)
  145.  
  146.     # Open a connection to the network device using ncclient
  147.     with manager.connect(
  148.         host=device["conn"]["host"],
  149.         port=device["conn"]["netconf_port"],
  150.         username=device["conn"]["username"],
  151.         password=device["conn"]["password"],
  152.         hostkey_verify=False,
  153.     ) as m:
  154.  
  155.         # print("Sending a <edit-config> operation to the device.\n")
  156.         # Make a NETCONF <get-config> query using the filter
  157.         netconf_reply = m.edit_config(netconf_data, target="running")
  158.  
  159.         if netconf_reply.ok:
  160.             print(
  161.                 "Device {} updated successfully".format(device["conn"]["host"])
  162.             )
  163.     print("")
  164.  
  165.     return netconf_reply
  166.  
  167.  
  168. def clear_ip(device):
  169.     """This function will clear the IP address on GigabitEthernet2
  170.    """
  171.     # MISSION TODO 5: What edit operation type is needed to clear details?
  172.     # Create an XML configuration template for openconfig-interfaces
  173.     netconf_interface_template = """
  174.    <config>
  175.        <interfaces xmlns="http://openconfig.net/yang/interfaces">
  176.            <interface>
  177.                <name>{name}</name>
  178.                <subinterfaces>
  179.                    <subinterface>
  180.                        <index>0</index>
  181.                        <ipv4 xmlns="http://openconfig.net/yang/interfaces/ip"
  182.                            operation="delete" />
  183.                        </ipv4>
  184.                    </subinterface>
  185.                </subinterfaces>
  186.            </interface>
  187.        </interfaces>
  188.    </config>"""
  189.     # END MISSION SECTION
  190.  
  191.     # Create NETCONF Payload for device
  192.     netconf_data = netconf_interface_template.format(name="GigabitEthernet2")
  193.  
  194.     # Uncomment the below lines to view the config payload
  195.     # print("The configuration payload to be sent over NETCONF.\n")
  196.     # print(netconf_data)
  197.  
  198.     # MISSION TODO 6: What Manager method is used to start a session?
  199.     # Open a connection to the network device using ncclient
  200.     with manager.connect(
  201.         host=device["conn"]["host"],
  202.         port=device["conn"]["netconf_port"],
  203.         username=device["conn"]["username"],
  204.         password=device["conn"]["password"],
  205.         hostkey_verify=False,
  206.     ) as m:
  207.         # END MISSION SECTION
  208.  
  209.         # print("Sending a <edit-config> operation to the device.\n")
  210.         # Make a NETCONF <get-config> query using the filter
  211.         netconf_reply = m.edit_config(netconf_data, target="running")
  212.  
  213.         if netconf_reply.ok:
  214.             print(
  215.                 "Device {} updated successfully".format(device["conn"]["host"])
  216.             )
  217.  
  218.     print("")
  219.  
  220.     return netconf_reply
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement