我已经能够编写一个解析IOS配置文件的python脚本,但是我收到了一个错误。
以下是剧本:
import glob, os
from ciscoconfparse import CiscoConfParse
os.chdir("T:/")
for cfgfile in glob.glob("*-confg"):
parse = CiscoConfParse("T:/" + cfgfile, factory=True, syntax='ios')
host = parse.find_objects_dna(r'Hostname')
interfaces_with_helpers = parse.find_parents_w_child( "^interf", "ip helper-address 10.194.35.201")
if interfaces_with_helpers:
print (host[0].hostname)
for interface in interfaces_with_helpers:
print (interface)
当我运行脚本时,它看起来很好,然后得到以下错误:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python34\lib\site-packages\ciscoconfparse-1.2.37-py3.4.egg\ciscoconfparse\ciscoconfparse.py", line 186, in __init__ CiscoConfParse=self)
File "C:\Python34\lib\site-packages\ciscoconfparse-1.2.37-py3.4.egg\ciscoconfparse\ciscoconfparse.py", line 2209, in __init__
self._list = self._bootstrap_obj_init(data)
File "C:\Python34\lib\site-packages\ciscoconfparse-1.2.37-py3.4.egg\ciscoconfparse\ciscoconfparse.py", line 2433, in _bootstrap_obj_init
syntax='ios')
File "C:\Python34\lib\site-packages\ciscoconfparse-1.2.37-py3.4.egg\ciscoconfparse\ciscoconfparse.py", line 2982, in ConfigLineFactory
comment_delimiter=comment_delimiter) # instance of the proper subclass
File "C:\Python34\lib\site-packages\ciscoconfparse-1.2.37-py3.4.egg\ciscoconfparse\models_cisco.py", line 1758, in __init__raise ValueError
ValueError
>>>
答案 0 :(得分:1)
对我来说看起来像一个意外的配置文件格式。如果您查看在CiscoConfParse库中抛出ValueError的源:
REGEX = r'^aaa\sgroup\sserver\s(?P<protocol>\S+)\s(?P<group>\S+)$'
mm = re.search(REGEX, self.text)
if not (mm is None):
groups = mm.groupdict()
self.protocol = groups.get('protocol', '')
self.group = groups.get('group', '')
else:
raise ValueError
看起来它偶然发现了一个配置文件,它希望该行满足正则表达式^aaa\sgroup\sserver\s(?P<protocol>\S+)\s(?P<group>\S+)$
并失败。
在迭代glob.glob("*-confg")
的结果时,您需要打印出当前使用的文件名,以查看哪个文件格式错误。然后更正此配置文件,或缩小您尝试解析的配置文件。
您也可以忽略错误,如下所示:
import glob, os
from ciscoconfparse import CiscoConfParse
os.chdir("T:/")
for cfgfile in glob.glob("*-confg"):
try:
parse = CiscoConfParse("T:/" + cfgfile, factory=True, syntax='ios')
except ValueError:
print "Malformed config file found. Skipping " + cfgfile
continue
host = parse.find_objects_dna(r'Hostname')
interfaces_with_helpers = parse.find_parents_w_child( "^interf", "ip helper-address 10.194.35.201")
if interfaces_with_helpers:
print (host[0].hostname)
for interface in interfaces_with_helpers:
print (interface)