我已经能够编写一个解析 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
>>>
请您参考如下方法:
在我看来,这是一种意想不到的配置文件格式。如果您查看 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)
