-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcrowl.py
280 lines (250 loc) · 14.4 KB
/
crowl.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: freenetwork
# e-mail: [email protected]
# site: vk.com/freenetwork
from commands import *
import re
COMMUNITY = 'YOUR_COMMUNITY'
# Состояние портов по документации
DEFAULT_STATE = {'1': 'disabled', '2': 'blocking', '3': 'listening', '4': 'learning', '5': 'forwarding', '6': 'broken', '7': 'BpduError'}
# Определяем стиль написания линий для линка. Красный пунктир для заблокированного порта.
STATE = {'1': '[color=white', '2': '[style=dashed, color=red', '3': '[color=black', '4': '[color=black', '5': '[color=black', '6': '[color=white', '7': '[color=red, style=dashed, penwidth=3.0'}
# Список классов. Список свичей.
list_of_Switch = []
class Switch():
def __init__(self):
self.hostname = ''
self.address = ''
self.neighbors = []
self.local_ports_for_neighbors = {}
self.local_ports = {}
self.local_ports_state = {}
self.local_ports_2_remote_ports = {}
def getPortState(self, search):
for key, value in self.local_ports_for_neighbors.iteritems():
for each in value:
if each == search:
if self.local_ports_state.has_key(key):
return self.local_ports_state[key]
else:
return 'error'
def getPortStateForDraw(self, search):
for key, value in self.local_ports_for_neighbors.iteritems():
for each in value:
if each == search:
if self.local_ports_state.has_key(key):
return STATE[self.local_ports_state[key]]
else:
return '[color=black'
def getPort(self, search):
for key, value in self.local_ports_for_neighbors.iteritems():
if search in value:
return key
def getPortNameOfIndex(self, key):
if key in self.local_ports:
return self.local_ports[key]
else:
return key
def getRemotePort(self, key):
return self.local_ports_2_remote_ports.get(key, [''])
print "Напишите имя файла с IP адресами: ",
filename = raw_input()
for line in open(filename) :
sw = Switch()
# Определенны переменные для запроса. Возвращают данные согласно названию переменной.
get_neighbors = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' 1.0.8802.1.1.2.1.4.1.1.9.0'
get_hostname = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' iso.3.6.1.2.1.1.5.0'
get_remote_ports_index_lldp = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' 1.0.8802.1.1.2.1.4.1.1.7.0'
get_remote_ports_index_lldp_2_local_port = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' 1.0.8802.1.1.2.1.4.1.1.7.0.'
get_remote_ports_name_lldp = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' 1.0.8802.1.1.2.1.4.1.1.8.0'
get_list_self_ports_index = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' iso.0.8802.1.1.2.1.3.7.1.3'
get_list_self_ports_name = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' iso.0.8802.1.1.2.1.3.7.1.4'
get_list_local_ports_index_lldp = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' iso.0.8802.1.1.2.1.4.1.1.4.0'
get_list_local_ports_state = 'snmpwalk -v2c -c '+COMMUNITY+' '+line.rstrip('\n')+' 1.3.6.1.2.1.17.2.15.1.3'
text = getoutput(get_hostname)
text = re.findall(r'"(.*?)"', text)
if len(text) > 0:
# Передаем адрес свичу
sw.hostname = text[0]
sw.address = line.rstrip('\n')
text = getoutput(get_neighbors)
# Получаем соседей свича
neighbors = re.findall(r'"(.*?)"', text)
# Получаем порты соседей свича
neighbors_ports = re.findall(r'1\.9\.0\.(.*?)\.[\d\.]', text)
i = 0
while i < len(neighbors):
if neighbors[i] == '':
i = i + 1
continue
else:
# Передаем соседей свича
sw.neighbors.append(neighbors[i])
# Передаем порты на которых находятся соседи. Порт ключ - соседи значение (массив)
sw.local_ports_for_neighbors.setdefault(neighbors_ports[i], []).append(neighbors[i])
i = i + 1
# Получаем список портов свича: индекс - имя
text = getoutput(get_list_self_ports_name)
# Определяем индекс локального порта
index = re.findall(r'iso\.0\.8802\.1\.1\.2\.1\.3\.7\.1\.4\.(.*?) =', text)
# Определяем имя удаленного хоста каждому опреденному выше порту
name = re.findall(r'"(.*?)"', text)
i = 0
while i < len(index):
# Передаем список портов свича: индекс - имя
sw.local_ports[index[i]] = name[i]
i = i + 1
text = getoutput(get_list_local_ports_state)
index = re.findall(r'iso\.3\.6\.1\.2\.1\.17\.2\.15\.1\.3\.(.*?) =', text)
state = re.findall(r'= INTEGER: (.)', text)
i = 0
while i < len(index):
# Передаем список портов свича: индекс - имя
sw.local_ports_state[index[i]] = state[i]
i = i + 1
for key, value in sw.local_ports_for_neighbors.iteritems():
text = getoutput(get_remote_ports_index_lldp_2_local_port+key)
name = re.findall(r'"(.*?)"', text)
for each in name:
sw.local_ports_2_remote_ports.setdefault(key, []).append(each)
# Добавляем полученную топологию в список сети. Дальше анализируем связи для построения графа.
# print sw.address
# print '-=-=-=-=-=-=-=-=-=-'
# print sw.hostname
# print '-=-=-=-=-=-=-=-=-=-'
# print sw.local_ports
# print '-=-=-=-=-=-=-=-=-=-'
# print sw.local_ports_state
# print '-=-=-=-=-=-=-=-=-=-'
# print sw.neighbors
# print '-=-=-=-=-=-=-=-=-=-'
# print sw.local_ports_for_neighbors
# print '-=-=-=-=-=-=-=-=-=-'
# print sw.local_ports_2_remote_ports
# print '-=-=-=-=-=-=-=-=-=-'
list_of_Switch.append(sw)
# Код для проверки полученных данных.
# i = 0
# while i < len(list_of_Switch):
# for each in list_of_Switch[i].neighbors:
# print each
## Разбираем словарь ключ:значение (индекс порта: имя порта)
# for key, value in list_of_Switch[i].local_ports.iteritems():
# print "%s-%s" % (key, value)
## Разбираем словарь ключ:значение (ключ:массив) где ключ номер порта, а значение (массив) его соседи
# for key, value in list_of_Switch[i].local_ports_for_neighbors.iteritems():
# print "%s" % (list_of_Switch[i].local_ports[key])
## Выводим список соседей предыдущего ключа (порта)
# print value
## Разбираем список локальных портов - для получения их состояния. Передаем каждый ключ методу класса для определения
## читаемого имени - индекс: имя. Так же передаем каждое значение от ключа для определения состояния порта.
# for key, value in list_of_Switch[i].local_ports_state.iteritems():
# print "%s-%s" % (list_of_Switch[i].getNamePortOfIndex(key), DEFAULT_STATE[value])
# i = i + 1
# Список свичей, в отредактированном виде. Для построения графа.
list_of_Graph = []
### Этот код проверка существования линка на массивах. Ниже тое самое но на словарях.
# Список линков в 1 направлении. Свич А - Свич Б
list_1_direction = []
# # Список линков в 2 направлении. Свич Б - Свич А
list_2_direction = []
def hasIndex(_key, _value):
if _key+':'+_value in list_1_direction:
return False
elif _value+':'+_key in list_1_direction:
return False
elif _key+':'+_value in list_2_direction:
return False
elif _value+':'+_key in list_2_direction:
return False
else:
list_1_direction.append(_key+':'+_value)
list_2_direction.append(_value+':'+_key)
return True
###
# #Список линков в 1 направлении. Свич А - Свич Б
# list_1_direction = {}
# # Список линков в 2 направлении. Свич Б - Свич А
# list_2_direction = {}
def getNeighborsPortState(_switch, _neighbor):
i = 0
while i < len(list_of_Switch):
if list_of_Switch[i].hostname == _neighbor:
statePortAnotherSide = list_of_Switch[i].getPortState(_switch)
if statePortAnotherSide == '2':
return 'Blocked'
if statePortAnotherSide == '1':
return 'Disabled'
else:
return 'None'
i = i + 1
# def hasIndex(_key, _value):
# if list_1_direction.get(_key, 'Null') == _value:
# print _key+': '+_value
# return False
# elif list_1_direction.get(_value, 'Null') == _key:
# print _key+': '+_value
# return False
# elif list_2_direction.get(_key, 'Null') == _value:
# print _key+': '+_value
# return False
# elif list_2_direction.get(_value, 'Null') == _key:
# print _key+': '+_value
# return False
# else:
# list_1_direction[_key] = _value
# list_2_direction[_value] = _key
# return True
class Graph():
def __init__(self):
self.hostname = ''
self.address = ''
self.neighbors = []
self.line = []
self.lineLabel = []
i = 0
while i < len(list_of_Switch):
graph = Graph()
graph.hostname = list_of_Switch[i].hostname
graph.address = list_of_Switch[i].address
for each in list_of_Switch[i].neighbors:
if re.match('CISCO', each) is not None:
continue
elif re.match('Cisco', each) is not None:
continue
elif hasIndex(graph.hostname, each) is True:
graph.neighbors.append(each)
lineLabel=', taillabel="'+list_of_Switch[i].getPortNameOfIndex(list_of_Switch[i].getPort(each))+'", headlabel="'+list_of_Switch[i].getRemotePort(list_of_Switch[i].getPort(each))[0]+'"'
graph.lineLabel.append(lineLabel)
if getNeighborsPortState(graph.hostname, each) == 'Blocked':
graph.line.append('[style=dashed, color=red')
elif getNeighborsPortState(graph.hostname, each) == 'Disabled':
graph.line.append('[color=white')
elif getNeighborsPortState(graph.hostname, each) == 'None':
graph.line.append(list_of_Switch[i].getPortStateForDraw(each))
else:
graph.line.append(list_of_Switch[i].getPortStateForDraw(each))
list_of_Graph.append(graph)
i = i + 1
print 'graph switches {'
# print 'overlap = false;'
# print 'label="Вильгельма Пика";'
# print 'node [shape=box, fontname="Times-Roman", fontsize=14, style=filled, color="#d3edea"]; splines="compound"'
print 'overlap=false; compound=true; esep=1; node [shape=box, fontname="Times-Roman", fontsize=14];'
for each in list_of_Graph:
print '"'+each.hostname+'"'+' [ label="'+each.address+'\\n'+each.hostname+'" image="switch.png" labelloc=b color="#ffffff"];'
for each in list_of_Graph:
hostname = each.hostname
i = 0
while i < len(each.neighbors):
print '"'+hostname+'" -- "'+each.neighbors[i]+'"'+each.line[i]+each.lineLabel[i]+', fontcolor="red" ];'
i = i + 1
print '}'
#Результат выполнения скрипта пишем в файл sheme.dot
#Затем работает graphviz
#sfdp -x -Goverlap=scale -Tpng sheme.dot -o sheme.png
# По окружности. График окружность.
#circo -x -Goverlap=scale -Tpng sheme.dot -o sheme.png
# По окружности. Ноды равноудаленны.
#circo -x -Tpng .dot -o sheme.png