0

我正在学习 Python 模块 ciscoconfparse 来循环遍历配置文件中的每个接口,并找到所有配置了 switchport 模式访问的接口。我用 find_blocks 方法解析了配置文件,它按如下预期输出结果。我还想遍历每个返回的接口并搜索 dot1x pae 身份验证器行。如果找到,则返回使用 dot1x pae 身份验证器配置的接口名称。我尝试了以下代码,但它还没有工作。请帮忙。谢谢

interface GigabitEthernet1/1
 switchport mode access
 switchport access vlan 10
 dot1x pae authenticator
interface GigabitEthernet1/2
 switchport mode access
 switchport voice vlan 154
 dot1x pae authenticator

代码如下:

import os
import re
import csv
from ciscoconfparse import CiscoConfParse
file_exists = os.path.isfile(r'c:\users\lang\documents\result.csv')
if not file_exists:
    with open (r'c:\users\lang\documents\result.csv', 'w', newline='') as csv_file:
        Header = ['Device', 'Vul ID', 'Exception', 'Status', 'Code', 'Severity', 'Reason']
        writer = csv.DictWriter(csv_file, fieldnames=Header)
        writer.writeheader()
def check_services():
    configs = (r'C:\Users\Lang\Documents\Tutorials\Python\Scripts\NetworkAudit\Data')

    for config in os.listdir(configs):
        if config.endswith(".txt"):
            filename = os.path.split(config)     #print(filename[1])
            parse = CiscoConfParse(config)
            all_intfs = parse.find_blocks('switchport mode access')
            for intf in all_intfs:
                print(intf)
                dot1x = re.search("^\sdot1x\spae\sauthenticator", all_intfs)
                print(dot1x)
check_services()
4

1 回答 1

1

You can get filtered result using following:

parse = CiscoConfParse(config)

# Return a list of all interfaces with switchport mode access
mode_access_intfs = parse.find_objects_w_child(r"^interf", r"switchport mode access")

# For each interface above, print out relevant information...
for obj in mode_access_intfs:

    # Find dot1x mode
    has_dotx = obj.re_match_iter_typed(r'^\s*(dot1x pae authenticator).*$', default='')

    if has_dotx:    
      # Print out what we found...
      print("-----")
      print("Object: {0}".format(obj))
      print("  Interface config line: {0}".format(obj.text))
      print("  has dotx mode: {0}".format(has_dotx))

Check on replit: https://replit.com/@arvindDhakad/QuickwittedOldlaceSet#main.py

examples: https://github.com/mpenning/ciscoconfparse/tree/master/examples

于 2021-09-29T19:09:44.767 回答