blob: 0ea392a4f45fe260786ad708e039c1ebb3b9a806 [file] [log] [blame]
Steve McIntyred6759dd2014-08-12 18:10:00 +01001#! /usr/bin/python
2
3# Copyright 2014 Linaro Limited
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18# MA 02110-1301, USA.
19
20import logging
21import pexpect
22import sys
Steve McIntyred6759dd2014-08-12 18:10:00 +010023import re
Steve McIntyre3dfd36f2015-02-12 06:37:56 +000024
Steve McIntyre72a8bce2015-01-23 18:02:19 +000025if __name__ == '__main__':
Steve McIntyrea67473a2015-02-12 08:26:33 +000026 import os
Steve McIntyre72a8bce2015-01-23 18:02:19 +000027 vlandpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
28 sys.path.insert(0, vlandpath)
29 sys.path.insert(0, "%s/.." % vlandpath)
30
Steve McIntyre5fa22652015-04-01 18:01:45 +010031from errors import InputError, PExpectError
Steve McIntyre17c421c2015-04-29 14:37:36 +010032from drivers.common import SwitchDriver, SwitchErrors
Steve McIntyred6759dd2014-08-12 18:10:00 +010033
34class CiscoCatalyst(SwitchDriver):
35
36 connection = None
Steve McIntyre3dfd36f2015-02-12 06:37:56 +000037 _username = None
38 _password = None
39 _enable_password = None
Steve McIntyre3f287882014-08-18 19:02:15 +010040
41 _capabilities = [
42 'TrunkWildCardVlans' # Trunk ports are on all VLANs by
43 # default, so we shouldn't need to
44 # bugger with them
45 ]
46
Steve McIntyred6759dd2014-08-12 18:10:00 +010047 # Regexp of expected hardware information - fail if we don't see
48 # this
Steve McIntyre1c8a3212015-07-14 17:07:31 +010049 _expected_descr_re = re.compile(r'WS-C\S+-\d+P')
Steve McIntyred6759dd2014-08-12 18:10:00 +010050
Steve McIntyre48dc6ae2014-12-23 16:08:19 +000051 def __init__(self, switch_hostname, switch_telnetport=23, debug = False):
Steve McIntyrebb58a272015-07-14 15:39:54 +010052 SwitchDriver.__init__(self, switch_hostname, debug)
Steve McIntyre5fa22652015-04-01 18:01:45 +010053 self._systemdata = []
Steve McIntyred6759dd2014-08-12 18:10:00 +010054 self.exec_string = "/usr/bin/telnet %s %d" % (switch_hostname, switch_telnetport)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +000055 self.errors = SwitchErrors()
Steve McIntyred6759dd2014-08-12 18:10:00 +010056
57 ################################
58 ### Switch-level API functions
59 ################################
60
Steve McIntyred6759dd2014-08-12 18:10:00 +010061 # Save the current running config into flash - we want config to
62 # remain across reboots
Steve McIntyre9b09b9d2014-09-24 15:08:10 +010063 def switch_save_running_config(self):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +000064 try:
65 self._cli("copy running-config startup-config")
66 self.connection.expect("startup-config")
67 self._cli("startup-config")
68 self.connection.expect("OK")
Steve McIntyre2d84e522015-02-12 06:44:42 +000069 except (PExpectError, pexpect.EOF):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +000070 # recurse on error
71 self._switch_connect()
72 self.switch_save_running_config()
Steve McIntyred6759dd2014-08-12 18:10:00 +010073
Steve McIntyre095b4452014-12-19 17:53:43 +000074 # Restart the switch - we need to reload config to do a
75 # roll-back. Do NOT save running-config first if the switch asks -
76 # we're trying to dump recent changes, not save them.
77 #
Steve McIntyre1c8a3212015-07-14 17:07:31 +010078 # This will also implicitly cause a connection to be closed
Steve McIntyre095b4452014-12-19 17:53:43 +000079 def switch_restart(self):
80 self._cli("reload")
81 index = self.connection.expect(['has been modified', 'Proceed'])
82 if index == 0:
83 self._cli("n") # No, don't save
84 self.connection.expect("Proceed")
85
86 # Fall through
87 self._cli("y") # Yes, continue to reset
88 self.connection.close(True)
89
Steve McIntyre3f287882014-08-18 19:02:15 +010090 # List the capabilities of the switch (and driver) - some things
91 # make no sense to abstract. Returns a dict of strings, each one
92 # describing an extra feature that that higher levels may care
93 # about
Steve McIntyre9b09b9d2014-09-24 15:08:10 +010094 def switch_get_capabilities(self):
Steve McIntyre3f287882014-08-18 19:02:15 +010095 return self._capabilities
Steve McIntyred6759dd2014-08-12 18:10:00 +010096
97 ################################
98 ### VLAN API functions
99 ################################
100
101 # Create a VLAN with the specified tag
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100102 def vlan_create(self, tag):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100103 logging.debug("Creating VLAN %d", tag)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000104 try:
105 self._configure()
106 self._cli("vlan %d" % tag)
107 self._end_configure()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100108
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000109 # Validate it happened
110 vlans = self.vlan_get_list()
111 for vlan in vlans:
112 if vlan == tag:
113 return
114 raise IOError("Failed to create VLAN %d" % tag)
115
116 except PExpectError:
117 # recurse on error
118 self._switch_connect()
119 self.vlan_create(tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100120
121 # Destroy a VLAN with the specified tag
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100122 def vlan_destroy(self, tag):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100123 logging.debug("Destroying VLAN %d", tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100124
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000125 try:
126 self._configure()
127 self._cli("no vlan %d" % tag)
128 self._end_configure()
129
130 # Validate it happened
131 vlans = self.vlan_get_list()
132 for vlan in vlans:
133 if vlan == tag:
134 raise IOError("Failed to destroy VLAN %d" % tag)
135
136 except PExpectError:
137 # recurse on error
138 self._switch_connect()
139 self.vlan_destroy(tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100140
141 # Set the name of a VLAN
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100142 def vlan_set_name(self, tag, name):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100143 logging.debug("Setting name of VLAN %d to %s", tag, name)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100144
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000145 try:
146 self._configure()
147 self._cli("vlan %d" % tag)
148 self._cli("name %s" % name)
149 self._end_configure()
150
151 # Validate it happened
152 read_name = self.vlan_get_name(tag)
153 if read_name != name:
154 raise IOError("Failed to set name for VLAN %d (name found is \"%s\", not \"%s\")"
155 % (tag, read_name, name))
156 except PExpectError:
157 # recurse on error
158 self._switch_connect()
159 self.vlan_set_name(tag, name)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100160
161 # Get a list of the VLAN tags currently registered on the switch
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100162 def vlan_get_list(self):
Steve McIntyred6759dd2014-08-12 18:10:00 +0100163 logging.debug("Grabbing list of VLANs")
Steve McIntyred6759dd2014-08-12 18:10:00 +0100164
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000165 try:
166 vlans = []
Steve McIntyred6759dd2014-08-12 18:10:00 +0100167
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100168 regex = re.compile(r'^ *(\d+).*(active)')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000169
170 self._cli("show vlan brief")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100171 for line in self._read_long_output("show vlan brief"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000172 match = regex.match(line)
173 if match:
174 vlans.append(int(match.group(1)))
175 return vlans
176
177 except PExpectError:
178 # recurse on error
179 self._switch_connect()
180 return self.vlan_get_list()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100181
182 # For a given VLAN tag, ask the switch what the associated name is
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100183 def vlan_get_name(self, tag):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000184
185 try:
Steve McIntyre5fa22652015-04-01 18:01:45 +0100186 logging.debug("Grabbing the name of VLAN %d", tag)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000187 name = None
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100188 regex = re.compile(r'^ *\d+\s+(\S+).*(active)')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000189 self._cli("show vlan id %d" % tag)
Steve McIntyre5fa22652015-04-01 18:01:45 +0100190 for line in self._read_long_output("show vlan id"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000191 match = regex.match(line)
192 if match:
193 name = match.group(1)
194 name.strip()
195 return name
196
197 except PExpectError:
198 # recurse on error
199 self._switch_connect()
200 return self.vlan_get_name(tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100201
202 ################################
203 ### Port API functions
Steve McIntyree1bf11a2014-08-14 17:56:25 +0100204 ################################
Steve McIntyred6759dd2014-08-12 18:10:00 +0100205
Steve McIntyre9936d002014-10-01 15:54:10 +0100206 # Set the mode of a port: access or trunk
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100207 def port_set_mode(self, port, mode):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100208 logging.debug("Setting port %s to %s", port, mode)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100209 if not self._is_port_mode_valid(mode):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000210 raise InputError("Port mode %s is not allowed" % mode)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100211 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000212 raise InputError("Port name %s not recognised" % port)
Steve McIntyre3f287882014-08-18 19:02:15 +0100213
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000214 try:
215 self._configure()
216 self._cli("interface %s" % port)
217 self._cli("switchport mode %s" % mode)
218 if mode == "trunk":
219 self._cli("switchport trunk encapsulation dot1q")
Steve McIntyre747050a2015-06-09 18:04:34 +0100220 self._cli("switchport trunk native vlan 1")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000221 self._end_configure()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100222
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000223 # Validate it happened
224 read_mode = self.port_get_mode(port)
Steve McIntyre3f287882014-08-18 19:02:15 +0100225
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000226 if read_mode != mode:
227 raise IOError("Failed to set mode for port %s" % port)
228
229 except PExpectError:
230 # recurse on error
231 self._switch_connect()
232 self.port_set_mode(port, mode)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100233
Steve McIntyre9936d002014-10-01 15:54:10 +0100234 # Get the mode of a port: access or trunk
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100235 def port_get_mode(self, port):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100236 logging.debug("Getting mode of port %s", port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100237 mode = ''
238 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000239 raise InputError("Port name %s not recognised" % port)
Steve McIntyre9936d002014-10-01 15:54:10 +0100240 regex = re.compile('Administrative Mode: (.*)')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000241
242 try:
243 self._cli("show interfaces %s switchport" % port)
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100244 for line in self._read_long_output("show interfaces switchport"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000245 match = regex.match(line)
246 if match:
247 mode = match.group(1)
248 if mode == 'static access':
249 return 'access'
250 if mode == 'dynamic auto':
251 return 'trunk'
252 return mode
253
254 except PExpectError:
255 # recurse on error
256 self._switch_connect()
257 return self.port_get_mode(port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100258
Steve McIntyre9936d002014-10-01 15:54:10 +0100259 # Set an access port to be in a specified VLAN (tag)
260 def port_set_access_vlan(self, port, tag):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100261 logging.debug("Setting access port %s to VLAN %d", port, tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100262 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000263 raise InputError("Port name %s not recognised" % port)
Steve McIntyre9936d002014-10-01 15:54:10 +0100264 if not (self.port_get_mode(port) == "access"):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000265 raise InputError("Port %s not in access mode" % port)
Steve McIntyre3f287882014-08-18 19:02:15 +0100266
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000267 try:
268 self._configure()
269 self._cli("interface %s" % port)
270 self._cli("switchport access vlan %d" % tag)
271 self._cli("no shutdown")
272 self._end_configure()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100273
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000274 # Finally, validate things worked
275 read_vlan = int(self.port_get_access_vlan(port))
276 if read_vlan != tag:
277 raise IOError("Failed to move access port %d to VLAN %d - got VLAN %d instead"
278 % (port, tag, read_vlan))
279
280 except PExpectError:
281 # recurse on error
282 self._switch_connect()
283 self.port_set_access_vlan(port, tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100284
Steve McIntyred6759dd2014-08-12 18:10:00 +0100285 # Add a trunk port to a specified VLAN (tag)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100286 def port_add_trunk_to_vlan(self, port, tag):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100287 logging.debug("Adding trunk port %s to VLAN %d", port, tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100288 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000289 raise InputError("Port name %s not recognised" % port)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100290 if not (self.port_get_mode(port) == "trunk"):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000291 raise InputError("Port %s not in trunk mode" % port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100292
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000293 try:
294 self._configure()
295 self._cli("interface %s" % port)
296 self._cli("switchport trunk allowed vlan add %d" % tag)
297 self._end_configure()
298
299 # Validate it happened
300 read_vlans = self.port_get_trunk_vlan_list(port)
301 for vlan in read_vlans:
302 if vlan == tag or vlan == "ALL":
303 return
304 raise IOError("Failed to add trunk port %s to VLAN %d" % (port, tag))
305
306 except PExpectError:
307 # recurse on error
308 self._switch_connect()
309 self.port_add_trunk_to_vlan(port, tag)
310
Steve McIntyred6759dd2014-08-12 18:10:00 +0100311 # Remove a trunk port from a specified VLAN (tag)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100312 def port_remove_trunk_from_vlan(self, port, tag):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100313 logging.debug("Removing trunk port %s from VLAN %d", port, tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100314 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000315 raise InputError("Port name %s not recognised" % port)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100316 if not (self.port_get_mode(port) == "trunk"):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000317 raise InputError("Port %s not in trunk mode" % port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100318
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000319 try:
320 self._configure()
321 self._cli("interface %s" % port)
322 self._cli("switchport trunk allowed vlan remove %d" % tag)
323 self._end_configure()
324
325 # Validate it happened
326 read_vlans = self.port_get_trunk_vlan_list(port)
327 for vlan in read_vlans:
328 if vlan == tag:
329 raise IOError("Failed to remove trunk port %s from VLAN %d" % (port, tag))
330
331 except PExpectError:
332 # recurse on error
333 self._switch_connect()
334 self.port_remove_trunk_from_vlan(port, tag)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100335
Steve McIntyre9936d002014-10-01 15:54:10 +0100336 # Get the configured VLAN tag for an access port (tag)
337 def port_get_access_vlan(self, port):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100338 logging.debug("Getting VLAN for access port %s", port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100339 vlan = 1
340 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000341 raise InputError("Port name %s not recognised" % port)
Steve McIntyre9936d002014-10-01 15:54:10 +0100342 if not (self.port_get_mode(port) == "access"):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000343 raise InputError("Port %s not in access mode" % port)
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100344 regex = re.compile(r'Access Mode VLAN: (\d+)')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000345
346 try:
347 self._cli("show interfaces %s switchport" % port)
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100348 for line in self._read_long_output("show interfaces switchport"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000349 match = regex.match(line)
350 if match:
351 vlan = match.group(1)
352 return int(vlan)
353
354 except PExpectError:
355 # recurse on error
356 self._switch_connect()
357 return self.port_get_access_vlan(port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100358
359 # Get the list of configured VLAN tags for a trunk port
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100360 def port_get_trunk_vlan_list(self, port):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100361 logging.debug("Getting VLANs for trunk port %s", port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100362 vlans = [ ]
363 if not self._is_port_name_valid(port):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000364 raise InputError("Port name %s not recognised" % port)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100365 if not (self.port_get_mode(port) == "trunk"):
Steve McIntyre72a8bce2015-01-23 18:02:19 +0000366 raise InputError("Port %s not in trunk mode" % port)
Steve McIntyre3f287882014-08-18 19:02:15 +0100367 regex_start = re.compile('Trunking VLANs Enabled: (.*)')
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100368 regex_continue = re.compile(r'\s*(\d.*)')
Steve McIntyre3f287882014-08-18 19:02:15 +0100369
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000370 try:
371 self._cli("show interfaces %s switchport" % port)
372
373 # Horrible parsing work - VLAN list may extend over several lines
374 in_match = False
375 vlan_text = ''
376
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100377 for line in self._read_long_output("show interfaces switchport"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000378 if in_match:
379 match = regex_continue.match(line)
380 if match:
381 vlan_text += match.group(1)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000382 else:
383 in_match = False
Steve McIntyre3f287882014-08-18 19:02:15 +0100384 else:
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000385 match = regex_start.match(line)
386 if match:
387 vlan_text += match.group(1)
388 in_match = True
Steve McIntyre3f287882014-08-18 19:02:15 +0100389
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000390 vlans = self._parse_vlan_list(vlan_text)
391 return vlans
Steve McIntyre3f287882014-08-18 19:02:15 +0100392
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000393 except PExpectError:
394 # recurse on error
395 self._switch_connect()
396 return self.port_get_trunk_vlan_list(port)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100397
398 ################################
399 ### Internal functions
400 ################################
401
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000402 # Connect to the switch and log in
403 def _switch_connect(self):
404
405 if not self.connection is None:
406 self.connection.close(True)
407 self.connection = None
408
Steve McIntyre5fa22652015-04-01 18:01:45 +0100409 logging.debug("Connecting to Switch with: %s", self.exec_string)
Steve McIntyre06c644a2015-07-17 17:07:41 +0100410 self.connection = pexpect.spawn(self.exec_string, logfile=self.logger)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000411 self._login()
412
413 # Avoid paged output
414 self._cli("terminal length 0")
415
416 # And grab details about the switch. in case we need it
417 self._get_systemdata()
418
419 # And also validate them - make sure we're driving a switch of
420 # the correct model! Also store the serial number
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100421 descr_regex = re.compile(r'^cisco\s+(\S+)')
422 sn_regex = re.compile(r'System serial number\s+:\s+(\S+)')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000423 descr = ""
424
425 for line in self._systemdata:
426 match = descr_regex.match(line)
427 if match:
428 descr = match.group(1)
429 match = sn_regex.match(line)
430 if match:
431 self.serial_number = match.group(1)
432
Steve McIntyre5fa22652015-04-01 18:01:45 +0100433 logging.debug("serial number is %s", self.serial_number)
434 logging.debug("system description is %s", descr)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000435
436 if not self._expected_descr_re.match(descr):
437 raise IOError("Switch %s not recognised by this driver: abort" % descr)
438
439 # Now build a list of our ports, for later sanity checking
440 self._ports = self._get_port_names()
441 if len(self._ports) < 4:
442 raise IOError("Not enough ports detected - problem!")
443
444 def _login(self):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100445 logging.debug("attempting login with username %s, password %s", self._username, self._password)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100446 self.connection.expect('User Access Verification')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000447 if self._username is not None:
Steve McIntyred6759dd2014-08-12 18:10:00 +0100448 self.connection.expect("User Name:")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000449 self._cli("%s" % self._username)
450 if self._password is not None:
Steve McIntyred6759dd2014-08-12 18:10:00 +0100451 self.connection.expect("Password:")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000452 self._cli("%s" % self._password, False)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100453 while True:
454 index = self.connection.expect(['User Name:', 'Password:', 'Bad passwords', 'authentication failed', r'(.*)(#|>)'])
455 if index != 4: # Any other means: failed to log in!
Steve McIntyre5fa22652015-04-01 18:01:45 +0100456 logging.error("Login failure: index %d\n", index)
457 logging.error("Login failure: %s\n", self.connection.match.before)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100458 raise IOError
459
460 # else
Steve McIntyre65dfe7f2015-06-09 15:57:02 +0100461 self._prompt_name = re.escape(self.connection.match.group(1).strip())
Steve McIntyred6759dd2014-08-12 18:10:00 +0100462 if self.connection.match.group(2) == ">":
463 # Need to enter "enable" mode too
464 self._cli("enable")
Steve McIntyread12cd72015-02-12 06:41:29 +0000465 if self._enable_password is not None:
Steve McIntyred6759dd2014-08-12 18:10:00 +0100466 self.connection.expect("Password:")
Steve McIntyread12cd72015-02-12 06:41:29 +0000467 self._cli("%s" % self._enable_password, False)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100468 index = self.connection.expect(['Password:', 'Bad passwords', 'authentication failed', r'(.*)(#|>)'])
469 if index != 3: # Any other means: failed to log in!
Steve McIntyre5fa22652015-04-01 18:01:45 +0100470 logging.error("Enable password failure: %s\n", self.connection.match)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100471 raise IOError
472 return 0
473
474 def _logout(self):
475 logging.debug("Logging out")
476 self._cli("exit", False)
477
478 def _configure(self):
479 self._cli("configure terminal")
480
481 def _end_configure(self):
482 self._cli("end")
483
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100484 def _read_long_output(self, text):
Steve McIntyre3f287882014-08-18 19:02:15 +0100485 prompt = self._prompt_name + '#'
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000486 try:
487 self.connection.expect(prompt)
488 except (pexpect.EOF, pexpect.TIMEOUT):
489 # Something went wrong; logout, log in and try again!
Steve McIntyre7a9c8192015-02-12 07:15:52 +0000490 logging.error("PEXPECT FAILURE, RECONNECT")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100491 self.errors.log_error_in(text)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000492 raise PExpectError("_read_long_output failed")
493 except:
Steve McIntyre5fa22652015-04-01 18:01:45 +0100494 logging.error("prompt is \"%s\"", prompt)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000495 raise
496
Steve McIntyre5fa22652015-04-01 18:01:45 +0100497 longbuf = []
Steve McIntyrea7cdefc2014-12-24 00:48:19 +0000498 for line in self.connection.before.split('\r\n'):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100499 longbuf.append(line.strip())
500 return longbuf
Steve McIntyred6759dd2014-08-12 18:10:00 +0100501
502 def _get_port_names(self):
503 logging.debug("Grabbing list of ports")
504 interfaces = []
505
506 # Use "Up" or "Down" to only identify lines in the output that
507 # match interfaces that exist
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100508 regex = re.compile(r'^\s*([a-zA-Z0-9_/]*).*(connect)(.*)')
Steve McIntyred6759dd2014-08-12 18:10:00 +0100509 regex1 = re.compile('.*Not Present.*')
Steve McIntyre6c279b42014-12-23 22:09:04 +0000510 regex2 = re.compile('.*routed.*')
Steve McIntyred6759dd2014-08-12 18:10:00 +0100511
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000512 try:
513 self._cli("show interfaces status")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100514 for line in self._read_long_output("show interfaces status"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000515 match = regex.match(line)
516 if match:
517 interface = match.group(1)
518 junk = match.group(3)
519 match1 = regex1.match(junk) # Deliberately drop things
520 # marked as "Not Present"
521 match2 = regex2.match(junk) # Deliberately drop things
522 # marked as "routed"
523 if not match1 and not match2:
524 interfaces.append(interface)
Steve McIntyred601ab82015-07-09 17:42:36 +0100525 logging.debug(" found %d ports on the switch", len(interfaces))
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000526 return interfaces
527
528 except PExpectError:
529 # recurse on error
530 self._switch_connect()
531 return self._get_port_names()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100532
Steve McIntyred6759dd2014-08-12 18:10:00 +0100533 def _show_config(self):
534 logging.debug("Grabbing config")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000535 try:
536 self._cli("show running-config")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100537 return self._read_long_output("show running-config")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000538 except PExpectError:
539 # recurse on error
540 self._switch_connect()
541 return self._show_config()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100542
543 def _show_clock(self):
544 logging.debug("Grabbing time")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000545 try:
546 self._cli("show clock")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100547 return self._read_long_output("show clock")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000548 except PExpectError:
549 # recurse on error
550 self._switch_connect()
551 return self._show_clock()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100552
Steve McIntyred6759dd2014-08-12 18:10:00 +0100553 def _get_systemdata(self):
Steve McIntyred6759dd2014-08-12 18:10:00 +0100554 logging.debug("Grabbing system sw and hw versions")
Steve McIntyreffb9b5a2014-10-10 16:31:58 +0100555
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000556 try:
557 self._systemdata = []
558 self._cli("show version")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100559 for line in self._read_long_output("show version"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000560 self._systemdata.append(line)
561
562 except PExpectError:
563 # recurse on error
564 self._switch_connect()
565 return self._get_systemdata()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100566
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000567 def _parse_vlan_list(self, inputdata):
Steve McIntyre3f287882014-08-18 19:02:15 +0100568 vlans = []
569
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000570 if inputdata == "ALL":
Steve McIntyre3f287882014-08-18 19:02:15 +0100571 return ["ALL"]
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000572 elif inputdata == "NONE":
Steve McIntyre3f287882014-08-18 19:02:15 +0100573 return []
574 else:
575 # Parse the complex list
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000576 groups = inputdata.split(',')
Steve McIntyre3f287882014-08-18 19:02:15 +0100577 for group in groups:
578 subgroups = group.split('-')
579 if len(subgroups) == 1:
580 vlans.append(int(subgroups[0]))
581 elif len(subgroups) == 2:
582 for i in range (int(subgroups[0]), int(subgroups[1]) + 1):
583 vlans.append(i)
584 else:
Steve McIntyre6d5594f2014-12-23 14:28:47 +0000585 logging.debug("Can't parse group \"" + group + "\"")
Steve McIntyre3f287882014-08-18 19:02:15 +0100586
587 return vlans
Steve McIntyred6759dd2014-08-12 18:10:00 +0100588
589 # Wrapper around connection.send - by default, expect() the same
590 # text we've sent, to remove it from the output from the
591 # switch. For the few cases where we don't need that, override
592 # this using echo=False.
593 # Horrible, but seems to work.
594 def _cli(self, text, echo=True):
595 self.connection.send(text + '\r')
596 if echo:
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000597 try:
598 self.connection.expect(text)
599 except (pexpect.EOF, pexpect.TIMEOUT):
600 # Something went wrong; logout, log in and try again!
Steve McIntyre7a9c8192015-02-12 07:15:52 +0000601 logging.error("PEXPECT FAILURE, RECONNECT")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000602 self.errors.log_error_out(text)
603 raise PExpectError("_cli failed on %s" % text)
604 except:
Steve McIntyrea67473a2015-02-12 08:26:33 +0000605 logging.error("Unexpected error: %s", sys.exc_info()[0])
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000606 raise
Steve McIntyred6759dd2014-08-12 18:10:00 +0100607
608if __name__ == "__main__":
Steve McIntyre48dc6ae2014-12-23 16:08:19 +0000609
610 import optparse
611
612 switch = 'vlandswitch01'
613 parser = optparse.OptionParser()
614 parser.add_option("--switch",
615 dest = "switch",
616 action = "store",
617 nargs = 1,
618 type = "string",
619 help = "specify switch to connect to for testing",
620 metavar = "<switch>")
621 (opts, args) = parser.parse_args()
622 if opts.switch:
623 switch = opts.switch
624
Steve McIntyre144d51c2015-07-07 17:56:30 +0100625 logging.basicConfig(level = logging.DEBUG,
626 format = '%(asctime)s %(levelname)-8s %(message)s')
Steve McIntyre48dc6ae2014-12-23 16:08:19 +0000627 p = CiscoCatalyst(switch, 23, debug=True)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100628 p.switch_connect(None, 'lngvirtual', 'lngenable')
Steve McIntyred6759dd2014-08-12 18:10:00 +0100629
630 print "VLANs are:"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100631 buf = p.vlan_get_list()
Steve McIntyre5fa22652015-04-01 18:01:45 +0100632 p.dump_list(buf)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100633
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100634 buf = p.vlan_get_name(2)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100635 print "VLAN 2 is named \"%s\"" % buf
636
637 print "Create VLAN 3"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100638 p.vlan_create(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100639
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100640 buf = p.vlan_get_name(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100641 print "VLAN 3 is named \"%s\"" % buf
642
643 print "Set name of VLAN 3 to test333"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100644 p.vlan_set_name(3, "test333")
Steve McIntyred6759dd2014-08-12 18:10:00 +0100645
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100646 buf = p.vlan_get_name(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100647 print "VLAN 3 is named \"%s\"" % buf
648
649 print "VLANs are:"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100650 buf = p.vlan_get_list()
Steve McIntyre5fa22652015-04-01 18:01:45 +0100651 p.dump_list(buf)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100652
653 print "Destroy VLAN 3"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100654 p.vlan_destroy(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100655
656 print "VLANs are:"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100657 buf = p.vlan_get_list()
Steve McIntyre5fa22652015-04-01 18:01:45 +0100658 p.dump_list(buf)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100659
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100660 buf = p.port_get_mode("Gi1/0/10")
Steve McIntyreb7adc782014-08-13 00:22:21 +0100661 print "Port Gi1/0/10 is in %s mode" % buf
662
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100663 buf = p.port_get_mode("Gi1/0/11")
Steve McIntyreb7adc782014-08-13 00:22:21 +0100664 print "Port Gi1/0/11 is in %s mode" % buf
Steve McIntyred6759dd2014-08-12 18:10:00 +0100665
Steve McIntyre9936d002014-10-01 15:54:10 +0100666 # Test access stuff
667 print "Set Gi1/0/9 to access mode"
668 p.port_set_mode("Gi1/0/9", "access")
Steve McIntyre3f287882014-08-18 19:02:15 +0100669
670 print "Move Gi1/0/9 to VLAN 4"
Steve McIntyre9936d002014-10-01 15:54:10 +0100671 p.port_set_access_vlan("Gi1/0/9", 4)
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100672
Steve McIntyre9936d002014-10-01 15:54:10 +0100673 buf = p.port_get_access_vlan("Gi1/0/9")
Steve McIntyre3f287882014-08-18 19:02:15 +0100674 print "Read from switch: Gi1/0/9 is on VLAN %s" % buf
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100675
Steve McIntyre3f287882014-08-18 19:02:15 +0100676 print "Move Gi1/0/9 back to VLAN 1"
Steve McIntyre9936d002014-10-01 15:54:10 +0100677 p.port_set_access_vlan("Gi1/0/9", 1)
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100678
Steve McIntyre9936d002014-10-01 15:54:10 +0100679 # Test access stuff
Steve McIntyre3f287882014-08-18 19:02:15 +0100680 print "Set Gi1/0/9 to trunk mode"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100681 p.port_set_mode("Gi1/0/9", "trunk")
Steve McIntyre3f287882014-08-18 19:02:15 +0100682 print "Read from switch: which VLANs is Gi1/0/9 on?"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100683 buf = p.port_get_trunk_vlan_list("Gi1/0/9")
Steve McIntyre5fa22652015-04-01 18:01:45 +0100684 p.dump_list(buf)
Steve McIntyre3f287882014-08-18 19:02:15 +0100685 print "Add Gi1/0/9 to VLAN 2"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100686 p.port_add_trunk_to_vlan("Gi1/0/9", 2)
Steve McIntyre3f287882014-08-18 19:02:15 +0100687 print "Add Gi1/0/9 to VLAN 3"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100688 p.port_add_trunk_to_vlan("Gi1/0/9", 3)
Steve McIntyre3f287882014-08-18 19:02:15 +0100689 print "Add Gi1/0/9 to VLAN 4"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100690 p.port_add_trunk_to_vlan("Gi1/0/9", 4)
Steve McIntyre3f287882014-08-18 19:02:15 +0100691 print "Read from switch: which VLANs is Gi1/0/9 on?"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100692 buf = p.port_get_trunk_vlan_list("Gi1/0/9")
Steve McIntyre5fa22652015-04-01 18:01:45 +0100693 p.dump_list(buf)
Steve McIntyre3f287882014-08-18 19:02:15 +0100694
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100695 p.port_remove_trunk_from_vlan("Gi1/0/9", 3)
696 p.port_remove_trunk_from_vlan("Gi1/0/9", 3)
697 p.port_remove_trunk_from_vlan("Gi1/0/9", 4)
Steve McIntyre3f287882014-08-18 19:02:15 +0100698 print "Read from switch: which VLANs is Gi1/0/9 on?"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100699 buf = p.port_get_trunk_vlan_list("Gi1/0/9")
Steve McIntyre5fa22652015-04-01 18:01:45 +0100700 p.dump_list(buf)
Steve McIntyre3f287882014-08-18 19:02:15 +0100701
Steve McIntyre7460d972014-12-23 14:45:30 +0000702# print 'Restarting switch, to explicitly reset config'
703# p.switch_restart()
Steve McIntyre3f287882014-08-18 19:02:15 +0100704
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100705# p.switch_save_running_config()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100706
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100707# p.switch_disconnect()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100708# p._show_config()