使用python解析mib文件
只需要替换文件地址和生成文件路径,
#coding=utf-8
import re
import json
def getMib():
trap_types=['OBJECT IDENTIFIER','OBJECT-TYPE','NOTIFICATION-TYPE','TRAP-TYPE'] #要获取的trap_type的类型
f = open('HW-IMAPV1NORTHBOUND-TRAP-MIB.mib','r',encoding='utf-8')
find_flag =False #查找 DESCRIPTION 和 VALUE标记
record_flag=False #记录 description标记
description_line = []
description = ''
name = ''
result = {}
enterprises='1.3.6.1.4.1' #每个mib文件可能引用了别的mib文件的对象 需要寻找初始值并添加
management='1.3.6.1.4.1.2011.2.15.1'
trap_name_value = {}
trap_name_value['enterprises'] = enterprises
trap_name_value['management'] = management
for line in f : #按行读入文件,此时line的type是str
if '--' in line: #过滤注释行
continue
if record_flag==False:
for trap_type in trap_types:
if trap_type in line: #检验是否到了要写入的内容
#print('LINE:', line)
find_flag=True #开启查找 DESCRIPTION 和 VALUE
name=line.split(trap_type)[0].strip() #取 trap_type 前面的内容作为trap_name
#print('NAME:',line.split(key)[0].strip())
break
if(find_flag):
if 'DESCRIPTION' in line:
record_flag=True #开启记录 description
if '::=' in line:
#print('LINE:', line)
value=line.split('::=')[1].strip()
#print('name:',name)
#print('description:',description)
#print('value:',get_str_btw(value,'{','}').strip())
trap_value=get_str_btw(value,'{','}').strip()
#print('VALUE:',line.split('::=')[1].strip())
if check_is_has_char(trap_value):
key=trap_value.split(' ')[0]
trap_value=trap_name_value[key]+'.'+trap_value.split(' ')[1]
trap_name_value[name] = trap_value
if trap_value not in result:
result[trap_value]={}
result[trap_value]['name']= name
result[trap_value]['desc'] = description
find_flag=False#关闭查找 DESCRIPTION 和 VALUE
record_flag=False#停止记录 description
description_line.clear()
continue
if(record_flag):
#print('LINE:', line)
K = list(line.strip())
if len(K) > 1: # 去除文本中的空行
for i in K: # 写入需要内容
description_line.append(i)
strlist = ''.join(description_line) # 合并列表元素
newlines = str(strlist).lstrip('DESCRIPTION')
description = newlines
#print('DESCRIPTION:',newlines)
return result
def get_str_btw(s, f, b):
'''提取字符串s中,字符串f和b的中间部分'''
if(s.find(f)>=0):
par = s.partition(f)
return (par[2].partition(b))[0][:]
else:
return s
def check_is_has_char(str):
'''查找是否含有字母'''
my_re = re.compile(r'[A-Za-z]',re.S)
res = re.findall(my_re,str)
if len(res):
return True
else:
return False
result = getMib()
print(getMib())
j = json.dumps(result)
reFile = open('mib.json','w')
reFile.write(str(j))
#print(getMib())