blob: 8e0d2846d74dcb38ab4163704228af79a8bff108 [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 McIntyre3dfd36f2015-02-12 06:37:56 +0000410 self.connection = pexpect.spawn(self.exec_string, logfile = self.logfile)
411
412 self._login()
413
414 # Avoid paged output
415 self._cli("terminal length 0")
416
417 # And grab details about the switch. in case we need it
418 self._get_systemdata()
419
420 # And also validate them - make sure we're driving a switch of
421 # the correct model! Also store the serial number
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100422 descr_regex = re.compile(r'^cisco\s+(\S+)')
423 sn_regex = re.compile(r'System serial number\s+:\s+(\S+)')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000424 descr = ""
425
426 for line in self._systemdata:
427 match = descr_regex.match(line)
428 if match:
429 descr = match.group(1)
430 match = sn_regex.match(line)
431 if match:
432 self.serial_number = match.group(1)
433
Steve McIntyre5fa22652015-04-01 18:01:45 +0100434 logging.debug("serial number is %s", self.serial_number)
435 logging.debug("system description is %s", descr)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000436
437 if not self._expected_descr_re.match(descr):
438 raise IOError("Switch %s not recognised by this driver: abort" % descr)
439
440 # Now build a list of our ports, for later sanity checking
441 self._ports = self._get_port_names()
442 if len(self._ports) < 4:
443 raise IOError("Not enough ports detected - problem!")
444
445 def _login(self):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100446 logging.debug("attempting login with username %s, password %s", self._username, self._password)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100447 self.connection.expect('User Access Verification')
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000448 if self._username is not None:
Steve McIntyred6759dd2014-08-12 18:10:00 +0100449 self.connection.expect("User Name:")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000450 self._cli("%s" % self._username)
451 if self._password is not None:
Steve McIntyred6759dd2014-08-12 18:10:00 +0100452 self.connection.expect("Password:")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000453 self._cli("%s" % self._password, False)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100454 while True:
455 index = self.connection.expect(['User Name:', 'Password:', 'Bad passwords', 'authentication failed', r'(.*)(#|>)'])
456 if index != 4: # Any other means: failed to log in!
Steve McIntyre5fa22652015-04-01 18:01:45 +0100457 logging.error("Login failure: index %d\n", index)
458 logging.error("Login failure: %s\n", self.connection.match.before)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100459 raise IOError
460
461 # else
Steve McIntyre65dfe7f2015-06-09 15:57:02 +0100462 self._prompt_name = re.escape(self.connection.match.group(1).strip())
Steve McIntyred6759dd2014-08-12 18:10:00 +0100463 if self.connection.match.group(2) == ">":
464 # Need to enter "enable" mode too
465 self._cli("enable")
Steve McIntyread12cd72015-02-12 06:41:29 +0000466 if self._enable_password is not None:
Steve McIntyred6759dd2014-08-12 18:10:00 +0100467 self.connection.expect("Password:")
Steve McIntyread12cd72015-02-12 06:41:29 +0000468 self._cli("%s" % self._enable_password, False)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100469 index = self.connection.expect(['Password:', 'Bad passwords', 'authentication failed', r'(.*)(#|>)'])
470 if index != 3: # Any other means: failed to log in!
Steve McIntyre5fa22652015-04-01 18:01:45 +0100471 logging.error("Enable password failure: %s\n", self.connection.match)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100472 raise IOError
473 return 0
474
475 def _logout(self):
476 logging.debug("Logging out")
477 self._cli("exit", False)
478
479 def _configure(self):
480 self._cli("configure terminal")
481
482 def _end_configure(self):
483 self._cli("end")
484
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100485 def _read_long_output(self, text):
Steve McIntyre3f287882014-08-18 19:02:15 +0100486 prompt = self._prompt_name + '#'
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000487 try:
488 self.connection.expect(prompt)
489 except (pexpect.EOF, pexpect.TIMEOUT):
490 # Something went wrong; logout, log in and try again!
Steve McIntyre7a9c8192015-02-12 07:15:52 +0000491 logging.error("PEXPECT FAILURE, RECONNECT")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100492 self.errors.log_error_in(text)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000493 raise PExpectError("_read_long_output failed")
494 except:
Steve McIntyre5fa22652015-04-01 18:01:45 +0100495 logging.error("prompt is \"%s\"", prompt)
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000496 raise
497
Steve McIntyre5fa22652015-04-01 18:01:45 +0100498 longbuf = []
Steve McIntyrea7cdefc2014-12-24 00:48:19 +0000499 for line in self.connection.before.split('\r\n'):
Steve McIntyre5fa22652015-04-01 18:01:45 +0100500 longbuf.append(line.strip())
501 return longbuf
Steve McIntyred6759dd2014-08-12 18:10:00 +0100502
503 def _get_port_names(self):
504 logging.debug("Grabbing list of ports")
505 interfaces = []
506
507 # Use "Up" or "Down" to only identify lines in the output that
508 # match interfaces that exist
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100509 regex = re.compile(r'^\s*([a-zA-Z0-9_/]*).*(connect)(.*)')
Steve McIntyred6759dd2014-08-12 18:10:00 +0100510 regex1 = re.compile('.*Not Present.*')
Steve McIntyre6c279b42014-12-23 22:09:04 +0000511 regex2 = re.compile('.*routed.*')
Steve McIntyred6759dd2014-08-12 18:10:00 +0100512
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000513 try:
514 self._cli("show interfaces status")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100515 for line in self._read_long_output("show interfaces status"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000516 match = regex.match(line)
517 if match:
518 interface = match.group(1)
519 junk = match.group(3)
520 match1 = regex1.match(junk) # Deliberately drop things
521 # marked as "Not Present"
522 match2 = regex2.match(junk) # Deliberately drop things
523 # marked as "routed"
524 if not match1 and not match2:
525 interfaces.append(interface)
Steve McIntyred601ab82015-07-09 17:42:36 +0100526 logging.debug(" found %d ports on the switch", len(interfaces))
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000527 return interfaces
528
529 except PExpectError:
530 # recurse on error
531 self._switch_connect()
532 return self._get_port_names()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100533
Steve McIntyred6759dd2014-08-12 18:10:00 +0100534 def _show_config(self):
535 logging.debug("Grabbing config")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000536 try:
537 self._cli("show running-config")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100538 return self._read_long_output("show running-config")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000539 except PExpectError:
540 # recurse on error
541 self._switch_connect()
542 return self._show_config()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100543
544 def _show_clock(self):
545 logging.debug("Grabbing time")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000546 try:
547 self._cli("show clock")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100548 return self._read_long_output("show clock")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000549 except PExpectError:
550 # recurse on error
551 self._switch_connect()
552 return self._show_clock()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100553
Steve McIntyred6759dd2014-08-12 18:10:00 +0100554 def _get_systemdata(self):
Steve McIntyred6759dd2014-08-12 18:10:00 +0100555 logging.debug("Grabbing system sw and hw versions")
Steve McIntyreffb9b5a2014-10-10 16:31:58 +0100556
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000557 try:
558 self._systemdata = []
559 self._cli("show version")
Steve McIntyref5fb22b2015-04-01 18:19:54 +0100560 for line in self._read_long_output("show version"):
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000561 self._systemdata.append(line)
562
563 except PExpectError:
564 # recurse on error
565 self._switch_connect()
566 return self._get_systemdata()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100567
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000568 def _parse_vlan_list(self, inputdata):
Steve McIntyre3f287882014-08-18 19:02:15 +0100569 vlans = []
570
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000571 if inputdata == "ALL":
Steve McIntyre3f287882014-08-18 19:02:15 +0100572 return ["ALL"]
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000573 elif inputdata == "NONE":
Steve McIntyre3f287882014-08-18 19:02:15 +0100574 return []
575 else:
576 # Parse the complex list
Steve McIntyre2b4c07b2014-12-22 16:10:04 +0000577 groups = inputdata.split(',')
Steve McIntyre3f287882014-08-18 19:02:15 +0100578 for group in groups:
579 subgroups = group.split('-')
580 if len(subgroups) == 1:
581 vlans.append(int(subgroups[0]))
582 elif len(subgroups) == 2:
583 for i in range (int(subgroups[0]), int(subgroups[1]) + 1):
584 vlans.append(i)
585 else:
Steve McIntyre6d5594f2014-12-23 14:28:47 +0000586 logging.debug("Can't parse group \"" + group + "\"")
Steve McIntyre3f287882014-08-18 19:02:15 +0100587
588 return vlans
Steve McIntyred6759dd2014-08-12 18:10:00 +0100589
590 # Wrapper around connection.send - by default, expect() the same
591 # text we've sent, to remove it from the output from the
592 # switch. For the few cases where we don't need that, override
593 # this using echo=False.
594 # Horrible, but seems to work.
595 def _cli(self, text, echo=True):
596 self.connection.send(text + '\r')
597 if echo:
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000598 try:
599 self.connection.expect(text)
600 except (pexpect.EOF, pexpect.TIMEOUT):
601 # Something went wrong; logout, log in and try again!
Steve McIntyre7a9c8192015-02-12 07:15:52 +0000602 logging.error("PEXPECT FAILURE, RECONNECT")
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000603 self.errors.log_error_out(text)
604 raise PExpectError("_cli failed on %s" % text)
605 except:
Steve McIntyrea67473a2015-02-12 08:26:33 +0000606 logging.error("Unexpected error: %s", sys.exc_info()[0])
Steve McIntyre3dfd36f2015-02-12 06:37:56 +0000607 raise
Steve McIntyred6759dd2014-08-12 18:10:00 +0100608
609if __name__ == "__main__":
Steve McIntyre48dc6ae2014-12-23 16:08:19 +0000610
611 import optparse
612
613 switch = 'vlandswitch01'
614 parser = optparse.OptionParser()
615 parser.add_option("--switch",
616 dest = "switch",
617 action = "store",
618 nargs = 1,
619 type = "string",
620 help = "specify switch to connect to for testing",
621 metavar = "<switch>")
622 (opts, args) = parser.parse_args()
623 if opts.switch:
624 switch = opts.switch
625
Steve McIntyre144d51c2015-07-07 17:56:30 +0100626 logging.basicConfig(level = logging.DEBUG,
627 format = '%(asctime)s %(levelname)-8s %(message)s')
Steve McIntyre48dc6ae2014-12-23 16:08:19 +0000628 p = CiscoCatalyst(switch, 23, debug=True)
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100629 p.switch_connect(None, 'lngvirtual', 'lngenable')
Steve McIntyred6759dd2014-08-12 18:10:00 +0100630
631 print "VLANs are:"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100632 buf = p.vlan_get_list()
Steve McIntyre5fa22652015-04-01 18:01:45 +0100633 p.dump_list(buf)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100634
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100635 buf = p.vlan_get_name(2)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100636 print "VLAN 2 is named \"%s\"" % buf
637
638 print "Create VLAN 3"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100639 p.vlan_create(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100640
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100641 buf = p.vlan_get_name(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100642 print "VLAN 3 is named \"%s\"" % buf
643
644 print "Set name of VLAN 3 to test333"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100645 p.vlan_set_name(3, "test333")
Steve McIntyred6759dd2014-08-12 18:10:00 +0100646
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100647 buf = p.vlan_get_name(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100648 print "VLAN 3 is named \"%s\"" % buf
649
650 print "VLANs are:"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100651 buf = p.vlan_get_list()
Steve McIntyre5fa22652015-04-01 18:01:45 +0100652 p.dump_list(buf)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100653
654 print "Destroy VLAN 3"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100655 p.vlan_destroy(3)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100656
657 print "VLANs are:"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100658 buf = p.vlan_get_list()
Steve McIntyre5fa22652015-04-01 18:01:45 +0100659 p.dump_list(buf)
Steve McIntyred6759dd2014-08-12 18:10:00 +0100660
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100661 buf = p.port_get_mode("Gi1/0/10")
Steve McIntyreb7adc782014-08-13 00:22:21 +0100662 print "Port Gi1/0/10 is in %s mode" % buf
663
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100664 buf = p.port_get_mode("Gi1/0/11")
Steve McIntyreb7adc782014-08-13 00:22:21 +0100665 print "Port Gi1/0/11 is in %s mode" % buf
Steve McIntyred6759dd2014-08-12 18:10:00 +0100666
Steve McIntyre9936d002014-10-01 15:54:10 +0100667 # Test access stuff
668 print "Set Gi1/0/9 to access mode"
669 p.port_set_mode("Gi1/0/9", "access")
Steve McIntyre3f287882014-08-18 19:02:15 +0100670
671 print "Move Gi1/0/9 to VLAN 4"
Steve McIntyre9936d002014-10-01 15:54:10 +0100672 p.port_set_access_vlan("Gi1/0/9", 4)
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100673
Steve McIntyre9936d002014-10-01 15:54:10 +0100674 buf = p.port_get_access_vlan("Gi1/0/9")
Steve McIntyre3f287882014-08-18 19:02:15 +0100675 print "Read from switch: Gi1/0/9 is on VLAN %s" % buf
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100676
Steve McIntyre3f287882014-08-18 19:02:15 +0100677 print "Move Gi1/0/9 back to VLAN 1"
Steve McIntyre9936d002014-10-01 15:54:10 +0100678 p.port_set_access_vlan("Gi1/0/9", 1)
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100679
Steve McIntyre9936d002014-10-01 15:54:10 +0100680 # Test access stuff
Steve McIntyre3f287882014-08-18 19:02:15 +0100681 print "Set Gi1/0/9 to trunk mode"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100682 p.port_set_mode("Gi1/0/9", "trunk")
Steve McIntyre3f287882014-08-18 19:02:15 +0100683 print "Read from switch: which VLANs is Gi1/0/9 on?"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100684 buf = p.port_get_trunk_vlan_list("Gi1/0/9")
Steve McIntyre5fa22652015-04-01 18:01:45 +0100685 p.dump_list(buf)
Steve McIntyre3f287882014-08-18 19:02:15 +0100686 print "Add Gi1/0/9 to VLAN 2"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100687 p.port_add_trunk_to_vlan("Gi1/0/9", 2)
Steve McIntyre3f287882014-08-18 19:02:15 +0100688 print "Add Gi1/0/9 to VLAN 3"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100689 p.port_add_trunk_to_vlan("Gi1/0/9", 3)
Steve McIntyre3f287882014-08-18 19:02:15 +0100690 print "Add Gi1/0/9 to VLAN 4"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100691 p.port_add_trunk_to_vlan("Gi1/0/9", 4)
Steve McIntyre3f287882014-08-18 19:02:15 +0100692 print "Read from switch: which VLANs is Gi1/0/9 on?"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100693 buf = p.port_get_trunk_vlan_list("Gi1/0/9")
Steve McIntyre5fa22652015-04-01 18:01:45 +0100694 p.dump_list(buf)
Steve McIntyre3f287882014-08-18 19:02:15 +0100695
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100696 p.port_remove_trunk_from_vlan("Gi1/0/9", 3)
697 p.port_remove_trunk_from_vlan("Gi1/0/9", 3)
698 p.port_remove_trunk_from_vlan("Gi1/0/9", 4)
Steve McIntyre3f287882014-08-18 19:02:15 +0100699 print "Read from switch: which VLANs is Gi1/0/9 on?"
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100700 buf = p.port_get_trunk_vlan_list("Gi1/0/9")
Steve McIntyre5fa22652015-04-01 18:01:45 +0100701 p.dump_list(buf)
Steve McIntyre3f287882014-08-18 19:02:15 +0100702
Steve McIntyre7460d972014-12-23 14:45:30 +0000703# print 'Restarting switch, to explicitly reset config'
704# p.switch_restart()
Steve McIntyre3f287882014-08-18 19:02:15 +0100705
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100706# p.switch_save_running_config()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100707
Steve McIntyre9b09b9d2014-09-24 15:08:10 +0100708# p.switch_disconnect()
Steve McIntyred6759dd2014-08-12 18:10:00 +0100709# p._show_config()