NXOSVlans.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #
  2. # Copyright (c) 2017-2018 Joe Clarke <jclarke@cisco.com>
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions
  7. # are met:
  8. # 1. Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. #
  14. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  15. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  18. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  20. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  21. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  22. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  23. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  24. # SUCH DAMAGE.
  25. from ncclient import manager
  26. import json
  27. import xmltodict
  28. import xml.dom.minidom
  29. import logging
  30. import os
  31. import pprint
  32. # logging.basicConfig(level=logging.DEBUG)
  33. class NXOSVlans():
  34. vlan_get = '''
  35. <show xmlns="http://www.cisco.com/nxos:1.0:vlan_mgr_cli">
  36. <vlan>
  37. <id>
  38. <vlan-id>{}</vlan-id>
  39. </id>
  40. </vlan>
  41. </show>
  42. '''
  43. vlan_add = '''
  44. <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
  45. <configure xmlns="http://www.cisco.com/nxos:1.0:vlan_mgr_cli">
  46. <__XML__MODE__exec_configure>
  47. <vlan>
  48. <vlan-id-create-delete>
  49. <__XML__PARAM_value>{}</__XML__PARAM_value>
  50. <__XML__MODE_vlan>
  51. <name>
  52. <vlan-name>{}</vlan-name>
  53. </name>
  54. <state>
  55. <vstate>active</vstate>
  56. </state>
  57. <no>
  58. <shutdown/>
  59. </no>
  60. </__XML__MODE_vlan>
  61. </vlan-id-create-delete>
  62. </vlan>
  63. </__XML__MODE__exec_configure>
  64. </configure>
  65. </config>
  66. '''
  67. vlan_delete = '''
  68. <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
  69. <configure xmlns="http://www.cisco.com/nxos:1.0:vlan_mgr_cli">
  70. <__XML__MODE__exec_configure>
  71. <no>
  72. <vlan>
  73. <vlan-id-create-delete>{}</vlan-id-create-delete>
  74. </vlan>
  75. </no>
  76. </__XML__MODE__exec_configure>
  77. </configure>
  78. </config>
  79. '''
  80. vlan_port_add = '''
  81. <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
  82. <configure>
  83. <__XML__MODE__exec_configure>
  84. <interface>
  85. <{}>
  86. <interface>{}</interface>
  87. <__XML__MODE_if-eth-{}-switch>
  88. <switchport>
  89. <trunk>
  90. <allowed>
  91. <vlan>
  92. <add>
  93. <add-vlans>{}</add-vlans>
  94. </add>
  95. </vlan>
  96. </allowed>
  97. </trunk>
  98. </switchport>
  99. </__XML__MODE_if-eth-{}-switch>
  100. </{}>
  101. </interface>
  102. </__XML__MODE__exec_configure>
  103. </configure>
  104. </config>
  105. '''
  106. vlan_port_delete = '''
  107. <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
  108. <configure>
  109. <__XML__MODE__exec_configure>
  110. <interface>
  111. <{}>
  112. <interface>{}</interface>
  113. <__XML__MODE_if-eth-{}-switch>
  114. <switchport>
  115. <trunk>
  116. <allowed>
  117. <vlan>
  118. <removed>
  119. <remove-vlans>{}</remove-vlans>
  120. </remove>
  121. </vlan>
  122. </allowed>
  123. </trunk>
  124. </switchport>
  125. </__XML__MODE_if-eth-{}-switch>
  126. </{}>
  127. </interface>
  128. </__XML__MODE__exec_configure>
  129. </configure>
  130. </config>
  131. '''
  132. def deploy_l2_vlan(self):
  133. with manager.connect_ssh(host=self.device, port=22, username=self.username, hostkey_verify=False, password=os.environ['NXOS_ADMIN_PW'], device_params={'name': 'nexus'}) as m:
  134. # See if the VLAN currently exists.
  135. try:
  136. res = m.get(('subtree', self.vlan_get.format(self.vid)))
  137. resd = xmltodict.parse(res.data_xml)
  138. if '__XML__OPT_Cmd_show_vlan_id___readonly__' in resd['data']['show']['vlan']['id']['vlan-id']:
  139. print('Error: VLAN {} already exists on {}'.format(
  140. self.vid, self.device))
  141. return False
  142. except Exception as e:
  143. print('Error getting VLAN {} from device {}: {}'.format(
  144. self.vid, self.device, e))
  145. return False
  146. # Create L2 VLAN.
  147. try:
  148. res = m.edit_config(
  149. target='running', config=self.vlan_add.format(self.vid, self.vname))
  150. except Exception as e:
  151. print('Error adding VLAN {} to device {}: {}'.format(
  152. self.vid, self.device, e))
  153. return False
  154. # Add L2 VLAN to trunk ports
  155. if self.trunks:
  156. good_config = False
  157. for trunk in self.trunks:
  158. rem = re.match(
  159. r'(ethernet|port-channel)(\d+)', trunk, re.I)
  160. if not rem:
  161. print(
  162. 'Error: trunk port {} is not a valid port name'.format(trunk))
  163. continue
  164. pname = rem.group(1).lower()
  165. try:
  166. m.edit_config(target='running', config=self.vlan_port_add.format(
  167. pname, rem.group(2), pname, self.vid, pname, pname))
  168. good_config = True
  169. except Exception as e:
  170. print('Error adding VLAN {} to port {}: {}'.format(
  171. self.vid, trunk, e))
  172. continue
  173. if not good_config:
  174. print('Error: Failed to add VLAN {} to any trunk ports on device {}'.format(
  175. self.vid, self.device))
  176. return False
  177. return True
  178. def delete_l2_vlan(self):
  179. with manager.connect_ssh(host=self.device, port=22, username=self.username, hostkey_verify=False, password=os.environ['NXOS_ADMIN_PW'], device_params={'name': 'nexus'}) as m:
  180. try:
  181. m.edit_config(target='running',
  182. config=self.vlan_delete.format(self.vid))
  183. except Exception as e:
  184. print('Error deleteing VLAN {} from device {}: {}'.format(
  185. self.vid, self.device, e))
  186. return False
  187. return True
  188. # XXX: This config is very specific to Cisco Live Europe
  189. def deploy_svi(self):
  190. with manager.connect_ssh(host=self.device, port=22, username=self.username, hostkey_verify=False, password=os.environ['NXOS_ADMIN_PW'], device_params={'name': 'nexus'}) as m:
  191. cmds = ['config t', 'no int vlan{}'.format(self.vid), 'int vlan{}'.format(self.vid), 'description {}'.format(
  192. self.description), 'no shutdown', 'no ip redirects', 'ip address {}'.format(self.ipv4), 'ip ospf network point-to-point', 'ip router ospf 1 area 0.0.0.0']
  193. if self.ipv6:
  194. cmds += ['ipv6 address {}'.format(
  195. self.ipv6), 'no ipv6 redirects', 'ipv6 router ospfv3 1 area 0.0.0.0']
  196. if self.hsrpv4:
  197. cmds += ['no ip arp gratuitous hsrp duplicate', 'hsrp version 2', 'hsrp 1', 'authentication md5 key-chain HSRP_KEY', 'preempt',
  198. 'priority {}'.format(self.hsrp_priority), 'timers 1 3', 'ip {}'.format(self.hsrpv4), 'track 3 decrement 20']
  199. if self.hsrpv6:
  200. cmds += ['hsrp 2 ipv6', 'authentication md5 key-chain HSRP_KEY', 'preempt', 'priority {}'.format(
  201. self.hsrp_priority), 'timers 1 3', 'ip {}'.format(self.hsrpv6), 'track 5 decrement 20']
  202. # print(pprint.pprint(cmds))
  203. try:
  204. m.exec_command(cmds)
  205. except Exception as e:
  206. print('Error adding SVI for VLAN {} to device {}: {}'.format(
  207. self.vid, self.device, e))
  208. return False
  209. return True
  210. def write_config(self):
  211. with manager.connect_ssh(host=self.device, port=22, username=self.username, hostkey_verify=False, password=os.environ['NXOS_ADMIN_PW'], device_params={'name': 'nexus'}) as m:
  212. try:
  213. m.exec_command(['copy running startup'])
  214. except Exception as e:
  215. print('Error copying running config to startup on {}: {}'.format(
  216. self.device, e))
  217. return False
  218. return True