-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshutil.py
executable file
·1210 lines (1042 loc) · 37.1 KB
/
sshutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Library of classes and functions for managing
Created on Nov 13, 2014
Library of functions and classes to use in other scripts.
@author: William.George
"""
# Standard Library Imports
import getpass
import time
import multiprocessing
import socket
import re
from collections import namedtuple
# Imports from other scripts in this project
from metrics import UpdateMetric
from sshexecute import sshrunP
import sshexecute
from metrics import DebugPrint
import metrics
from collections import namedtuple
# TODO: FIX THIS MESS
DEBUG = True
ARP_TABLE = []
DEFAULT_GATEWAY = None
CREDENTIALS = None # SET THESE IN MAIN()!
CURRENT_SWITCH = None
def deduplicate_list(oList, tag=None):
"""Given oList, search for duplicates.
If found, print information to screen to assist in troubleshooting
"""
nList = []
for item in oList:
if item in nList:
index = nList.index(item)
if DEBUG:
print ('******\n{2}\nDuplicate Entry!!\nOld:{0}\nNew:{1}\n'
'******'.format(repr(nList[index]), repr(item), tag))
nList[index] = item
else:
nList.append(item)
return nList
def listify(obj):
"""Return obj if it's already a list, package it in a list and return it if
it's not.
"""
if type(obj) == list:
rslt = obj
else:
rslt = [obj]
return rslt
def format_mac_address(oMac):
"""Ensure a MAC address (or fragment) is formatted consistent with the
Cisco show commands. If it's 4 characters, return it unmodified.
If it's 12 or more characters, remove any '.' or '-', and format it
'the Cisco Way'; return.
"""
if oMac is None:
return None
elif len(oMac) == 4:
rslt = oMac
elif len(oMac) >= 12:
wMac = oMac.replace('-', '')
wMac = wMac.replace('.', '')
rslt = '.'.join([wMac[:4], wMac[4:8], wMac[8:]])
else:
raise Exception('I don\'t know how to process this MAC Address!')
return rslt.lower()
def format_interface_name(oInterface, short=False):
"""
Ensure consistent formatting of interface names.
long form unless short == True
"""
# TODO: The whole way this works is dumb, and will match any string that starts with the letter 'e'.
Formats = {
'gi': ['Gi', 'GigabitEthernet'],
'fa': ['Fa', 'FastEthernet'],
'e': ['E', 'Ethernet'],
'vl': ['Vl', 'Vlan'],
'se': ['Se', 'Serial'],
'te': ['Te', 'TenGigabitEthernet'],
'po': ['Po', 'Port-Channel'],
'tu': ['Tu', 'Tunnel']
}
if oInterface in ['', None]:
return oInterface
iInterface = oInterface.lower()
prefix = iInterface[:2]
if prefix in Formats:
lName = Formats[prefix][1]
sName = Formats[prefix][0]
elif prefix[0] in Formats:
prefix = prefix[0]
lName = Formats[prefix][1]
sName = Formats[prefix][0]
else:
raise Exception(ValueError)
buff = iInterface.strip(lName.lower())
if short:
nName = sName
else:
nName = lName
nInterface = nName + buff
return nInterface
def get_credentials(user=None):
"""
Prompt user for password. Use username if provided,
otherwise, assume current logged in user.
"""
password = None
if user is None or user == '':
user = getpass.getuser()
while password is None or password == '':
password = getpass.getpass('Password:')
return (user, password)
def DateTime():
"""Return current time as dd/mm/yyyy - hh:mm:ss"""
DTFormat = "%d/%m/%Y - %H:%M:%S"
rslt = time.strftime(DTFormat)
return rslt
def Date():
"""Return current Date as dd/mm/yyyy"""
DTFormat = "%d/%m/%Y"
rslt = time.strftime(DTFormat)
return rslt
class EndDevice(object):
"""Represent an end device"""
def __init__(self, mac=None, ip=None, switchport=None, switch=None,
dns=None):
self.mac = mac
self.ip = ip
self._switch = switch
self._switchport = switchport
self.dns = dns
@property
def mac(self):
return self._mac
@mac.setter
def mac(self, value):
self._mac = format_mac_address(value)
@property
def switchport(self):
return self._switchport
@switchport.setter
def switchport(self, port): # could be SwitchPort or str
if not isinstance(self.switch, Switch):
self._switchport = format_interface_name(str(port))
# if switch is str, this must also be str
return
# raise Exception('can\'t set \'EndDevice({0}).switchport({1})\'
# before .switch has a real object '.format(self,port))
if type(port) == str:
port = format_interface_name(port)
# if it's a string, make sure it's formatted properly
# even if it's a string, we don't create an object yet, because it
# could already be created and in place
if port not in self.switch.ports:
if type(port) == str:
self.switch.ports += [SwitchPort(name=port)]
else:
self.switch.ports += port
index = self.switch.ports.index(port)
devices = self.switch.ports[index].devices
if self not in devices:
devices += [self]
self._switchport = self.switch.ports[index]
@property
def switch(self):
return self._switch
@switch.setter
def switch(self, switch):
# needs to be an actual Switch or None or String
if type(switch) == str:
self._switch = switch
return
# raise Exception('Need to pass an actual switch object to
# EndDevice.switch')
self._switch = switch
if self._switch is None:
return
devices = self.switch.devices
if self not in devices:
self.switch.devices += [self]
else:
self.switch.devices[self.switch.devices.index(self)] = self
def __repr__(self):
return ('EndDevice(mac={0}, ip={1}, dns={2}, switch={3}, '
'switchport={4})'.format(self.mac, self.ip, self.dns,
self.switch, self.switchport))
def __str__(self):
return self.mac
def __eq__(self, other):
return (self.mac == str(other)) or (self.ip == str(other))
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
return NotImplemented
def __le__(self, other):
return NotImplemented
def __ge__(self, other):
return NotImplemented
def __gt__(self, other):
return NotImplemented
class NetworkDevice(object):
def __init__(self, ip='None', creds=None): # str ip
self._ip = 'None'
self.ip = ip
if creds is None:
raise SyntaxError('No Credentials Specified')
self.credentials = creds
self.goodstates = ['UNK', 'UP']
self.state = 'UNK' # valid states: ['UNK', 'UP', 'DOWN']
self.connection = None
@property
def ip(self):
return self._ip
@ip.setter
def ip(self, arg):
# TODO: implement ipaddress class, at that time evaluate permitting integer values
if type(arg) in [str, type(None)]:
self._ip = str(arg)
else:
raise Exception('can\'t set \'Switch({0}).ip\' to {1}'
''.format(self, type(arg)))
def _connect(self):
if self.connection is None:
self.connection = sshexecute.SSHConnection(self.ip,
self.credentials,
True)
def execute(self, command, trim=True, timeout=1.5):
"""
Connect to switch and execute 'command'
"""
self._connect()
UpdateMetric('Switch.execute')
try:
lines = self.connection.run(command=command,
trim=trim,
timeout=timeout)
except Exception:
self.state = 'DOWN'
raise
else:
self.state = 'UP'
return lines
class Riverbed(NetworkDevice):
pass
class Switch(NetworkDevice):
"""
represent a switch, contains clSwitchPorts and references
to their clEndDevices
"""
def __init__(self, ip='None', creds=None): # str ip
NetworkDevice.__init__(self, ip, creds)
self.ports = []
self.devices = []
self.cdp_information = {}
self._mac_address_table = ''
self.populate_lite_time = None
@property
def hostname(self):
"""
Cisco Specific
:return:
"""
if not self.supported:
return 'UNK'
for line in self.startup_config.splitlines():
if 'hostname' in line:
return line.split()[-1]
return ''
@property
def supervisor(self):
"""
Cisco Specific
:return:
"""
if not self.supported:
return 'UNK'
_supervisor = getattr(self, '_supervisor', None)
if _supervisor is not None:
return _supervisor
_supervisor = ''
for line in self.execute('show module').splitlines():
if 'supervisor' in line.lower():
_supervisor = line.split()[-2]
self._supervisor = _supervisor
return self._supervisor
@property
def flash(self):
"""
Cisco Specific
:return:
"""
if not self.supported:
return 'UNK'
_flash = getattr(self, '_flash', None)
if _flash is not None:
return _flash
FlashSpace = namedtuple('FlashSpace', 'free, total')
# filesystems = ['bootdisk:', 'flash:', 'bootflash:',
# 'sup-bootflash:', 'slot0:']
rslt = self.execute('dir')
if any([word in rslt.lower() for word in ('invalid', 'error')]):
return 'UNK'
rslt = rslt.splitlines()[-1]
fs = FlashSpace(*reversed([int(sub.split()[0]) for sub in rslt.split('(')]))
# FlashSpace(free=xxxx, total=yyyy)
self._flash = fs
return self._flash
# for filesystem in reversed(filesystems):
# rslt = self.execute('dir {0}'.format(filesystem))
# if 'Invalid input' not in rslt and 'Error' not in rslt:
# line = rslt.splitlines()[-1]
# #fs = FreeSpace(line.split()[-3].strip('('),
# # line.split()[0])
# #return fs
# return filesystem, line, self.execute('dir').splitlines()[-1]
@property
def available_ram(self):
"""
Cisco Specific
:return:
"""
if not self.supported:
return 'UNK'
regex = re.compile(r'[^K/0-9.]').search
search = lambda x: 'K' in x and not bool(regex(x))
# looking for '#####K' or '#####K/#####K' etc.
for line in self.version.splitlines():
if 'bytes of memory' in line or \
'bytes of physical memory' in line:
for word in line.split():
if search(word):
break
break
else:
return ''
word = word.split('/')
add = lambda x, y: x + int(y.strip('K'))
rslt = reduce(add, word, 0)
return rslt
@property
def model(self):
"""
Deduces this switches model number from 'sh ver' output.
This will fail gracefully to 'UNK', but 'Switch.supported' will return False in
this case and many features will refuse to run.
:return:
"""
if self.state == 'UP':
for line in self.version.splitlines():
if 'bytes of' in line.lower():
return line.split()[1]
return 'UNK'
@property
def supported(self):
if self.model == 'UNK':
return False
return True
@property
def stacked(self):
"""
whether or not the switch represents or is a member of a stack
:return: bool
"""
if not self.supported:
return 'UNK'
version = self.version
stackable = False
stacklines = []
for index, line in enumerate(version.splitlines()):
if stackable:
if not line:
break
elif '-' in line.split()[0]:
continue
stacklines.append(line)
continue
if 'switch ports model' in line.lower():
stackable = True
if len(stacklines) > 1:
return True
return False
@property
def license(self):
if not self.supported:
return 'UNK'
try:
return self._license
except AttributeError:
self._collect_license()
return self._license
def _collect_license(self):
regex = re.compile(r'\(..*\),')
try:
word = regex.findall(self.version)[0]
except IndexError:
word = 'UNK'
else:
# sanity checks, if we're not sure, just suppress.
for char in ['(', ')', ',']:
if word.count(char) > 1:
word = 'UNK'
break
else:
word = word.split('-')[1]
if 'UNIVERSAL' in word.upper():
rslt = self._read_universal_license()
word = '{0} ({1})'.format(word, rslt)
self._license = word
def _read_universal_license(self):
"""
Will return string in form: "(featureset, featureset)" if multiple valid
featuresets found. Otherwise "featureset".
:return:
"""
sh_license = self.execute('sh license')
index = 0
licenses = {}
rslts = []
if '% Incomplete' in sh_license:
license_options = self.execute('sh license ?')
if 'summary' in license_options:
sh_license = self.execute('sh license summary')
elif 'right-to-use' in license_options:
rtu = self.execute('sh license right-to-use')
for line in rtu.splitlines():
if 'permanent' in line:
return line.split()[1]
# return 'UNK'
raise Exception(rtu)
for line in sh_license.splitlines():
words = [word.strip() for word in line.split(':')]
if line.startswith('Index'):
index = words[0].split()[1]
feature = words[-1]
licenses[index] = {'feature': feature}
continue
licenses[index][words[0].lower()] = words[-1]
for license in licenses.values():
t_words = {'License State': 'active', 'License Type': 'permanent'} # words to test for, all must hit
for key, value in t_words.items():
if value not in license.get(key.lower(), '').lower():
break
else:
rslts.append(license['feature'])
if len(rslts) == 1:
return rslts[0]
elif len(rslts) > 1:
return str(rslts)
else:
return 'UNK'
@property
def software_version(self):
if not self.supported:
return 'UNK'
_sw_version = getattr(self, '_sw_version', None)
if _sw_version is not None:
return _sw_version
version = self.version
if 'IOS-XE' in version:
regex = re.compile(r'Version.*RELEASE')
else:
regex = re.compile(r'Version.*,')
_sw_version = regex.findall(self.version)[0].strip(',').split()[1]
self._sw_version = _sw_version
return _sw_version
@property
def version(self):
"""
Cisco Specific
:return:
"""
try:
return self._version
except AttributeError:
self._collect_version()
return self._version
@property
def startup_config(self):
"""
Cisco Specific
:return:
"""
try:
return self._startup_config
except AttributeError:
self._collect_startup_config()
return self._startup_config
def _collect_startup_config(self):
"""
Cisco Specific
:return:
"""
self._startup_config = self.execute('show startup-config')
def _collect_version(self, data=False):
"""
Pull Version info
"""
command = 'sh ver'
UpdateMetric('Switch._collect_version')
try:
rBuffer = self.execute(command)
except:
raise
self._version = rBuffer
@property
def ports(self):
return self._ports
@ports.setter
def ports(self, arg):
if type(arg) == list:
self._ports = arg
i = 0
while i < len(arg):
if isinstance(arg[i], basestring):
self.ports[i] = SwitchPort(name=self.ports[i],
switch=self)
elif (self.ports[i].switch != self):
self.ports[i].switch = self
i += 1
else:
raise Exception('can\'t set \'Switch({0}).ports\''
'with {1}'.format(self, type(arg)))
@property
def devices(self):
return self._devices
@devices.setter
def devices(self, arg):
if type(arg) == list:
self._devices = arg
else:
raise Exception('can\'t set \'Switch({0}).devices\' with {1}'
''.format(self, type(arg)))
def populate(self):
"""
Run all of this switches 'collect' methods. Typically faster
than running them one by one at different times because you never
have to rebuild the connection, etc...
"""
metrics.DebugPrint('[{0}].populate()'.format(self.ip))
# need an IP and creds to start.
if self.ip == 'None' or not self.credentials:
metrics.DebugPrint('Attempt to populate switch data missing IP'
'and/or creds', 3)
raise Exception('missing IP or creds')
metrics.DebugPrint('[{0}].._get_interfaces()'.format(self.ip))
self._get_interfaces()
if self.state not in self.goodstates:
metrics.DebugPrint('[{0}].populate failed! State: {1}'
''.format(self.ip, self.state))
return self.state
metrics.DebugPrint('[{0}].._classify_ports()'.format(self.ip))
self._classify_ports()
metrics.DebugPrint('[{0}].._collect_cdp_information()'.format(self.ip))
self._collect_cdp_information()
metrics.DebugPrint('[{0}]..collect_mac_table()'.format(self.ip))
self.collect_mac_table()
metrics.DebugPrint('[{0}].._collect_interface_descriptions()'
''.format(self.ip))
self._collect_interface_descriptions()
self._collect_version()
return self.state
def populate_lite(self):
if self.ip == 'None' or not self.credentials:
metrics.DebugPrint('Attempt to populate switch data missing IP'
'and/or creds', 3)
raise Exception('missing IP or creds')
start_time = time.time()
self._collect_startup_config()
self._collect_version()
self._collect_license()
self.populate_lite_time = time.time() - start_time
_ = self.flash
_ = self.supervisor
def collect_mac_table(self):
"""
Connect to switch and pull MAC Address table
"""
command = 'sh mac address-table'
UpdateMetric('Switch.collect_mac_table')
lines = self.execute(command)
self._mac_address_table = '\n'.join(
[x for x in lines.splitlines() if 'dynamic' in x.lower()])
@property
def mac_table(self):
if not self._mac_address_table:
self.collect_mac_table()
table = self._mac_address_table
return table
def _get_interfaces(self, data=False):
"""
Return all interfaces on a switch, including stats
"""
command = 'show interface'
UpdateMetric('Switch._get_interfaces')
if not data:
try:
lines = self.execute(command).splitlines()
except:
self.state = 'DOWN'
return []
else:
lines = data.splitlines()
self.state = 'UP'
detail = []
first = True
for line in lines:
try:
format_interface_name(line.split()[0], True)
except Exception:
pass
else:
if (not first and 'line protocol' in line):
port = SwitchPort(detail=('\n'.join(detail)),
switch=self)
self.ports.append(port)
detail = []
else:
first = False
detail.append(line)
# Don't forget the last one...
port = SwitchPort(detail=('\n'.join(detail)), switch=self)
self.ports.append(port)
def _collect_cdp_information(self, data=False):
"""
Apply CDP neighbor information to self.ports[]
ex. switch.ports[1].CDPneigh[0] == (
NeighborID,
NeighborIP,
NeighborCapabilities,
NieghborPort)
"""
command = 'sh cdp ne det'
UpdateMetric('Switch._collect_cdp_information')
try:
rBuffer = self.execute(command)
except:
raise
spLines = rBuffer.splitlines()
CDPEntries = {}
for line in spLines:
# print line
if line.split() == []:
continue
cat = line.split()[0].lower()
if 'device' in cat:
cdpid = ''.join(line.split()[2:])
elif 'ip' == cat:
ip = line.split()[2]
elif 'platform' in cat:
i = 0
while i < len(line.split()):
word = line.split()[i]
if 'capabilit' in word.lower():
capindex = i + 1
i += 1
caps = line.split()[capindex:]
elif 'interface' in cat:
interface = line.split()[1].strip(':,')
neighborinterface = line.split()[-1]
CDPEntries[interface.lower()] = (cdpid, ip, caps,
neighborinterface)
for switchport in self.ports:
if switchport.name.lower() in CDPEntries:
switchport.CDPneigh.append(CDPEntries[switchport.name.lower()])
self.cdp_information = CDPEntries
def _classify_ports(self, data=False):
"""
Classify ports by switchport mode.
('access', 'trunk')
"""
name = ''
switchport = ''
mode = ''
command = 'sh int switchport'
UpdateMetric('Switch._classify_ports')
if data:
rBuffer = data.strip()
else:
if self.state not in self.goodstates:
return
try:
rBuffer = self.execute(command)
except:
raise
spLines = rBuffer.splitlines()
DebugPrint('Switch.ports: {0}'.format(self.ports))
for line in spLines:
if 'Name:' in line:
name = format_interface_name(line.split()[-1])
switchport = ''
mode = ''
elif 'Switchport:' in line:
switchport = line.split()[-1]
elif 'Operational Mode:' in line:
mode = line.split()[-1]
# if switchport == 'Enabled' and mode == 'access':
DebugPrint('Classifying {0}'.format(name))
try:
i = self.ports.index(name)
except:
DebugPrint('TRYING TO CLASSIFY PORT {0} THAT DOESN\'T'
' EXIST ON {1}'.format(name, self.ip), 3)
continue
port = self.ports[i]
port.switchportMode = mode
port.switchport = switchport
def _collect_interface_descriptions(self, data=False):
"""
Apply existing interface descriptions to
switch.ports[] ex. switch.ports[1].description = 'Trunk to
ABQCore1'
"""
command = 'sh int description'
UpdateMetric('_collect_interface_descriptions')
if not (self.state in self.goodstates):
return
try:
rBuffer = self.execute(command)
except:
raise
spLines = rBuffer.splitlines()[1:]
for switchport in self.ports:
name = format_interface_name(str(switchport), short=True)
try:
line = next(x for x in spLines if name in x)
except StopIteration:
#print 'Unexpected StopIteration!'
#print 'switch =', self.ip
#print 'Port = ', name
#print 'Data:'
#print spLines
raise Exception('Failure in _collect_interface_descriptions')
spLine = re.split('\s\s+', line)
if len(spLine) >= 4:
description = ' '.join(spLine[3:]).strip()
else:
description = ''
switchport.description = description
def _get_end_devices(self):
rslt = []
scrubbedInterfaceList = []
scrubbedMACAddressTable = []
for port in self.ports:
metrics.DebugPrint('[{0}].[{1}].edge: {2}'.format(self.ip,
port.name,
port.edge))
if port.edge:
scrubbedInterfaceList.append(port)
DebugPrint('[{0}]._get_end_devices.len(scrubbedInterfaceList): {1}'
''.format(self.ip, len(scrubbedInterfaceList)), 1)
DebugPrint('[{0}]._get_end_devices.scrubbedInterfaceList: {1}'
''.format(self.ip, scrubbedInterfaceList), 0)
macAddressTable = self.mac_table
DebugPrint('[{0}]._get_end_devices.len(macAddressTable): {1}'
''.format(self.ip, len(macAddressTable.splitlines())), 1)
DebugPrint('[{0}]._get_end_devices.macAddressTable: {1}'
''.format(self.ip, macAddressTable), 0)
for interface in scrubbedInterfaceList:
for line in macAddressTable.splitlines():
if line.strip().endswith(format_interface_name(str(interface),
short=True)):
scrubbedMACAddressTable.append(line.strip())
for line in scrubbedMACAddressTable:
mac = format_mac_address(line.split()[1])
port = line.split()[-1]
ed = EndDevice()
ed.mac = mac
ed.switch = self
ed.switchport = port
rslt.append(ed)
rslt = deduplicate_list(rslt, 'returning from _get_end_devices')
return rslt
def __repr__(self):
return ('Switch(ip={0}, Ports={1}, Devices={2})'
''.format(self.ip, len(self.ports), len(self.devices)))
def __str__(self):
return self.ip
def __eq__(self, other):
return (self.ip == str(other))
def __ne__(self, other):
return not (self == other)
class SwitchPort(object):
"""
Represent ports attached to a Switch. Contains
EndDevice objects and reference to its parent
Switch.
"""
def __init__(self, name=None, switch=None, switchportMode=None,
detail=None):
# str ip, Switch switch
self.stats = {}
self.switchportMode = switchportMode
self.CDPneigh = []
self.devices = []
self.switch = switch
self.switchport = ''
self._detail = ''
self.status = ''
self.description = ''
self._name = None
if detail:
self.detail = detail
else:
self.name = name
self._edge = True
@property
def CDPneigh(self):
return self._CDPneigh
@CDPneigh.setter
def CDPneigh(self, arg):
if type(arg) == list or arg is None:
self._CDPneigh = arg
else:
raise Exception('can\'t set \'SwitchPort({0}).CDPneigh\' with '
'{1}'.format(self, type(arg)))
@property
def devices(self):
return self._devices
@devices.setter
def devices(self, arg):
if type(arg) == list:
self._devices = arg
i = 0
while i < len(arg):
if type(self.devices[i]) == str:
self.devices[i] = EndDevice(mac=self.devices[i],
switch=self)
elif (self.devices[i].swtich != self):
self.devices[i].switch = self
i += 1
else:
raise Exception('can\'t set \'SwitchPort({0}).devices\' with '
'{1}'.format(self, type(arg)))
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if value is None:
self._name = value
else:
self._name = format_interface_name(value)
@property
def switchportMode(self):
if self._switchportMode:
return self._switchportMode
else:
return 'access'
@switchportMode.setter
def switchportMode(self, value):
if type(value) == str:
value = value.lower()
if value in ('access', 'trunk', None):
self._switchportMode = value
else:
self._switchportMode = 'unknown'
@property
def detail(self):