-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmib-browser.py
302 lines (266 loc) · 9.85 KB
/
mib-browser.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
import argparse
import re
from pathlib import Path
from typing import List, Optional
class RawMibItem:
def __init__(self, name: str, parent: str, index: int, mib_name: str):
self.name: str = name
self.parent: str = parent
self.index: int = index
self.mib_name: str = mib_name
class RawMib:
def __init__(self, mibname: str):
self.name: str = mibname
self.items: List[RawMibItem] = []
def add_item(self, name: str, parent: str, index: int):
self.items.append(RawMibItem(name, parent, index, self.name))
class Node:
def __init__(self, name, oid, mib_name=None):
self.name = name
if not mib_name:
mib_name = "(unknown MIB)"
self.mib_name = mib_name
self.oid = oid
self.subnodes = []
def add_subnode(self, name, number, mib_name=None):
subnode = Node(name, self.oid + "." + str(number), mib_name)
self.subnodes.append(subnode)
self.subnodes.sort(key=oid_sort_func)
return subnode
def oid_sort_func(node):
"""Returns the last number in node's OID for sorting the subnodes"""
try:
return int(node.oid.split(".")[-1])
except:
return 0
def find_node(node, name):
"""Finds a node based on its name, returns Node"""
if node.name == name:
return node
for subnode in node.subnodes:
found_node = find_node(subnode, name)
if found_node:
return found_node
return None
def find_item_in_all_mibs(all_mibs: List[RawMib], item_name: str):
for mib in all_mibs:
for item in mib.items:
if item.name == item_name:
return item
return None
def add_item(mibtree: Node, all_mibs: List[RawMib], item: RawMibItem):
"""Adds the item in the MIB tree, recursively creating the parent
items as well if needed."""
node = find_node(mibtree, item.name)
if node:
return True
parent_item = find_item_in_all_mibs(all_mibs, item.parent)
if not parent_item:
return False
result = add_item(mibtree, all_mibs, parent_item)
if result:
parent_node = find_node(mibtree, parent_item.name)
parent_node.add_subnode(item.name, item.index, item.mib_name)
return True
return False
def print_list(node):
print("{} = {}::{}".format(node.oid, node.mib_name, node.name))
for subnode in node.subnodes:
print_list(subnode)
root_mib = RawMib("(root)")
root_mib.add_item("iso", "", 1)
all_mibs: List[RawMib] = [ root_mib ]
all_mib_files: dict = {}
missing_imports = {}
missed_mibs = []
def load_mib_by_name(mib_name: str):
if mib_name not in all_mib_files:
global missed_mibs
if mib_name not in missed_mibs:
print(f"MIB '{mib_name}' not found")
missed_mibs.append(mib_name)
return False
mib = None
name_waiting = None
prev_line = None
more_needed = False
imported_items = []
parsing_imports = False
global all_mibs
imports = {}
with open(all_mib_files[mib_name]) as input_file:
for line in input_file:
line = line.strip()
cols = line.split()
if name_waiting:
if "::=" not in line:
continue
name = name_waiting
name_waiting = None
match = re.search(r"::=\s*\{\s*([\w-]+)\s+([0-9]+)\s*\}", line)
parent = match[1]
number = match[2]
# Added to the tree later below
elif parsing_imports:
words = re.split(r"[, ]+", line)
i = 0
while i < len(words):
if words[i] != "FROM":
if words[i]:
imported_items.append(words[i])
else:
imported_from = words[i+1]
i += 1
if imported_from.endswith(";"):
parsing_imports = False
imported_from = imported_from[:-1]
for item in imported_items:
imports[item] = imported_from
imported_items = []
i += 1
continue
elif line == "" or line.startswith("--") or line.find(",") >= 0 or cols[0] == "SYNTAX":
continue
elif (
len(cols) == 2 and cols[1] in [
"OBJECT-IDENTITY",
"OBJECT-TYPE",
"MODULE-IDENTITY",
"NOTIFICATION-TYPE",
]) or (
len(cols) == 3 and cols[1] == "OBJECT" and cols[2] == "IDENTIFIER"
):
# Save the name and keep looping
name_waiting = cols[0]
continue
elif "DEFINITIONS" in cols and "::=" in cols and "BEGIN" in cols:
# "mibname DEFINITIONS ::= BEGIN"
mib_name = cols[0]
if mib:
all_mibs.append(mib)
mib = RawMib(mib_name)
continue
elif more_needed:
line = prev_line + " " + line
more_needed = False
elif line.find("OBJECT IDENTIFIER") >= 0:
if line == "OBJECT IDENTIFIER":
continue
elif line.find(")") >= 0:
continue
elif line.find("::=") == -1:
# We need to read more to find the assignment
more_needed = True
prev_line = line
continue
elif line.startswith("OBJECT IDENTIFIER"):
# Let's take the previous line as well
line = prev_line + " " + line
match = re.search(r"([\w-]+)\s*OBJECT IDENTIFIER\s*::=\s*\{\s*([\w-]+)\s*([0-9]+)\s*\}", line)
name = match[1]
parent = match[2]
number = match[3]
elif line.startswith("IMPORTS"):
imported_items = []
parsing_imports = True
words = re.split(r"[, ]+", line)
if len(words) == 1:
continue
i = 1 # Skip the first word "IMPORTS"
while i < len(words):
if words[i] != "FROM":
imported_items.append(words[i])
else:
imported_from = words[i+1]
i += 1
if imported_from.endswith(";"):
parsing_imports = False
imported_from = imported_from[:-1]
for item in imported_items:
imports[item] = imported_from
imported_items = []
i += 1
continue
else:
prev_line = line
continue
#print("{} = {{ {} {} }}".format(name, parent, number))
if parent != "0": # Skip zeroDotZero
mib.add_item(name, parent, int(number))
if mib:
global missing_imports
for item, mib_name in imports.items():
if not load_mib_by_name(mib_name):
missing_imports[item] = mib_name
all_mibs.append(mib)
return True
def get_mib_name_from_file(path: Path) -> Optional[str]:
"""Returns the MIB name from the MIB file."""
with open(path) as f:
try:
for line in f:
line = line.strip()
match = re.search(r"^([\w-]+)\s+DEFINITIONS\s*::=\s*BEGIN", line)
if match:
return match[1]
except UnicodeDecodeError:
return None
return None
def get_all_mibs(path: Path):
"""Returns all MIB names with their file names."""
mib_files: dict = {}
for p in path.glob("*"):
if p.is_file():
mib_name = get_mib_name_from_file(p)
if mib_name:
mib_files[mib_name] = p
elif p.is_dir():
mib_files.update(get_all_mibs(p))
return mib_files
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"mib_name",
metavar="mibname",
help="The name of the MIB to be shown",
)
parser.add_argument(
"-a", "--add",
metavar="path(s)",
help="Add given path(s) (comma-separated) to MIB search list",
dest="add_paths",
required=False,
)
parser.add_argument(
"-n", "--no-default",
help="Do not use the default MIB search path",
required=False,
action="store_true",
)
args = parser.parse_args()
searchpath = [] if args.no_default else ["/var/lib/snmp/mibs"]
if args.add_paths:
searchpath += args.add_paths.split(",")
global all_mib_files
for path in searchpath:
all_mib_files.update(get_all_mibs(Path(path)))
load_mib_by_name(args.mib_name)
mibtree = Node("iso", ".1", "(root)")
missing_items = set()
for mib in all_mibs:
for item in mib.items:
if not add_item(mibtree, all_mibs, item):
if item.parent in missing_items:
missing_items.add(item.name)
elif item.parent in missing_imports:
print("Missing input: MIB file for {} is needed for resolving \"{} = {{ {} {} }}\" (and others in the same tree)".format(
missing_imports[item.parent], item.name, item.parent, item.index,
))
missing_items.add(item.name)
else:
print("Missing input: parent {0} was not found for \"{1} = {{ {0} {2} }}\"".format(
item.parent, item.name, item.index,
))
print_list(mibtree)
if __name__ == "__main__":
main()