2015-09-08 60 views
2

我已經能夠編寫解析IOS配置文件的python腳本,但出現錯誤。運行python腳本解析IOS配置文件時出現錯誤信息

下面是腳本:

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 
>>> 

回答

1

看起來像一個意外的配置文件格式我。如果你看看那裏的ValueError異常在CiscoConfParse庫被拋出來源:

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) 
+0

感謝你這麼多,該訣竅。非常感激!! – Jason