当前位置: 首页 > news >正文

python三方库_ciscoconfparse学习笔记

文章目录

    • 介绍
    • 使用
    • 基本原理
      • 父子关系
    • 属性
      • ioscfg 获取配置信息,返回列表
      • is_config_line 判断是否是配置行
      • is_intf 判断IOSCfgLine是不是interface
      • is_subintf 判断IOSCfgLine是不是子接口
      • lineage 不知道用法
      • is_ethernet_intf 判断IOSCfgLine是否是以太网接口
      • is_loopback_intf 判断IOSCfgLine是不是loopback接口
      • intf_in_portchannel 判断接口是否在port-channel中
      • portchannel_number 返回port-channel的序号
    • 方法
      • find_objects() 检索文本
      • find_objects_w_child在父对象中检索特定文本
      • re_match 使用regex搜索IOSCfgLine文本并返回整数索引处的正则表达式组
      • re_match_iter_typed()获取配置的值
      • re_match_typed
      • re_search 使用regex搜索此IOSCfgLine的文本
      • re_search_children 使用regex搜索此子级中包含的文本
    • 实例
      • 获取所有接口(interface)
      • 获取包含特定配置的父配置
      • 将接口名称和槽位建立关联
      • 获取接口名称和接口描述
      • 获取接口名称和IPv4地址

介绍

  1. 文档
  2. github
  3. 虽然项目名称为ciscoconfparse,但可以分析华为等格式类似的设备
  4. 安装
    1. 全新安装
      pip3 install ciscoconfparse
      
    2. 升级安装
      pip3 install --upgrade ciscoconfparse
      
    3. 安装指定版本
      pip install ciscoconfparse==1.5.6
      

使用

  1. 导入库
  2. 创建对象
  3. 代码
    from ciscoconfparse import CiscoConfParse
    file1 = "/mnt/share/bak/pc1/share/IDC网络运维表格/备份文件/20210506/SW03.txt"
    cisco_cfg = CiscoConfParse(file1)
    

基本原理

父子关系

  1. 以缩进定义父子关系,
  2. 示例
    policy-map QOS_1class GOLDpriority percent 10class SILVERbandwidth 30random-detectclass default
    !
    
  3. 示例说明
    1. 第1行为父级
    2. 第2 4 7 行为第1行的子级
    3. 第3行是第2行的子级

属性

ioscfg 获取配置信息,返回列表

  1. 返回的是list类型
  2. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface port-channel1',' ip address 112.54.105.38/30','!','interface Ethernet1/1',' channel-group 1 mode active',' no shutdown','interface Ethernet1/2',' no shutdown','!',]
    parse = CiscoConfParse(config)   
    cfg = parse.ioscfg
    print(type(cfg))
    print(cfg)
    
  3. 示例输出
    <class 'list'>
    ['!', 'interface port-channel1', ' ip address 112.54.105.38/30', '!', 'interface Ethernet1/1', ' channel-   group 1 mode active', ' no shutdown', 'interface Ethernet1/2', ' no shutdown', '!']
    

is_config_line 判断是否是配置行

  1. 如果是配置行返回True
  2. 如果是空行、注释行么返回False
  3. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['interface Ethernet1/2',' no shutdown','!',]
    parse = CiscoConfParse(config)
    obj1 = parse.find_objects('^!')[0]
    obj2 = parse.find_objects('no shutdown')[0]
    print(obj1.is_config_line)
    print(obj2.is_config_line)
    

is_intf 判断IOSCfgLine是不是interface

  1. 返回的是布尔值
  2. 子接口也是接口
  3. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface Serial1/0',' ip address 1.1.1.1 255.255.255.252','!','interface ATM2/0',' no ip address','!','interface ATM2/0.100 point-to-point',' ip address 1.1.1.5 255.255.255.252',' pvc 0/100','  vbr-nrt 704 704','!',]
    parse = CiscoConfParse(config)
    obj = parse.find_objects('^interface\sSerial')[0]
    print(obj.is_intf)
    obj = parse.find_objects('^interface\sATM')[0]
    print(obj.is_intf)
    

is_subintf 判断IOSCfgLine是不是子接口

  1. 用法同上

lineage 不知道用法

is_ethernet_intf 判断IOSCfgLine是否是以太网接口

  1. 返回布尔值
  2. 任何以太网接口(10M到10G)都被视为以太网接口
  3. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['interface port-channel1',' no shutdown','!','interface Ethernet1/2',' no shutdown','!',]
    parse = CiscoConfParse(config)   
    obj1 = parse.find_objects('interface port-channel1')[0]
    obj2 = parse.find_objects('interface Ethernet1/2')[0]
    print(obj1.is_ethernet_intf  )
    print(obj2.is_ethernet_intf )
    
  4. 示例输出
    False
    True
    

is_loopback_intf 判断IOSCfgLine是不是loopback接口

  1. 判断是不是loopback接口
  2. 返回的是布尔值
  3. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface FastEthernet1/0',' ip address 1.1.1.1 255.255.255.252','!','interface Loopback0',' ip address 1.1.1.5 255.255.255.255','!',]
    parse = CiscoConfParse(config)
    obj = parse.find_objects(r'^interface\sFast')[0]
    print(obj.is_loopback_intf)
    obj = parse.find_objects(r'^interface\sLoop')[0]
    print(obj.is_loopback_intf)
    

intf_in_portchannel 判断接口是否在port-channel中

  1. 返回的是布尔值,表示接口是否在port-channel中
  2. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface port-channel1',' ip address 112.54.105.38/30','!','interface Ethernet1/1',' channel-group 1 mode active',' no shutdown','interface Ethernet1/2',' no shutdown','!',]
    parse = CiscoConfParse(config)   
    interface1 = parse.find_objects('^interface Ethernet1/1')
    interface2 = parse.find_objects('^interface Ethernet1/2')
    print ("interface1:",interface1[0].intf_in_portchannel)
    print ("interface2:",interface2[0].intf_in_portchannel)
    
  3. 示例输出
    interface1: True
    interface2: False
    

portchannel_number 返回port-channel的序号

  1. 返回的是int类型
  2. 如果不属于任何port-channel,则返回-1
  3. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['interface port-channel1',' no shutdown','!','interface Ethernet1/1',' channel-group 2 mode active',' no shutdown','interface Ethernet1/2',' no shutdown','!',]
    parse = CiscoConfParse(config)
    obj1 = parse.find_objects('^interface Ethernet1/1')[0]
    obj2 = parse.find_objects('^interface Ethernet1/2')[0]
    print(obj1.portchannel_number)
    print(obj2.portchannel_number)
    
  4. 示例输出
    2
    -1
    

方法

find_objects() 检索文本

  1. 在对象中查找特定文本
  2. 语法
    配置对象.find_objects("文本内容(可用正则)")
    
  3. 示例
    1. 查找cisco-nxos中所有trunk组
      # 获取所有接口
      interfaces = cisco_cfg.find_objects("^interface port-channel")
      # 打印索引值为3的接口
      print(interfaces[3])
      # 打印所有接口名称
      for obj in interfaces:print(obj.text)
      

find_objects_w_child在父对象中检索特定文本

  1. 在父对象中检索特定文本
  2. 语法
    配置对象.find_objects_w_child(parentspec=r"父对象包含的文本", childspec=r"子对象中包含的文本")
    
  3. 示例,获取所有二层接口(N7K为例)
    # 获取所有二层接口
    interfaces = cisco_cfg.find_objects_w_child(parentspec=r"^interface", childspec=r"switchport")
    # 打印所有接口名称
    for obj in interfaces:print(obj.text)
    

re_match 使用regex搜索IOSCfgLine文本并返回整数索引处的正则表达式组

  1. 介绍
    1. 使用regex搜索IOSCfgLine文本并返回整数索引处的正则表达式组
  2. 语法
    re_match(regex, group=1, default='')
    
  3. 选项
    选项类型说明
    regexstr字符串或python正则表达式,应该匹配。此正则表达式应包含括号,括号用于绑定匹配组
    groupint一个整数,指定要返回的所需正则表达式组。组默认为1
    defaultstr如果不匹配,则返回默认值。默认情况下,如果不匹配,则返回空字符串。
    返回结果str正则表达式组匹配的文本;如果不匹配,则返回默认值。
  4. 示例,打印接口下的子网掩码
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface Serial1/0',' ip address 1.1.1.1 255.255.255.248','!','interface Serial1/1',' ip address 1.1.1.5 255.255.255.252','!',]
    parse = CiscoConfParse(config)
    for obj in parse.find_objects(r'ip\saddress'):netmask = obj.re_match(r'1\.1\.1\.5\s(\S+)')
    print("The netmask is", netmask)
    
  5. 示例输出
    The netmask is 255.255.255.252
    

re_match_iter_typed()获取配置的值

  1. 语法
    re_match_iter_typed(regex, group=1, result_type=<class 'str'>, default='', untyped_default=False, recurse=False)
    
  2. 选项
    选项说明
    regex字符串,字符串或python正则表达式,应该匹配。此正则表达式应包含括号,括号用于绑定匹配组
    group整数,一个整数,指定要返回的所需正则表达式组。组默认为1。
    result_type类型,一种类型(通常是str、int、float或IPv4Obj中的一种)。所有返回值都转换为结果类型,默认为str
    default任意,如果不匹配,则返回默认值
    untyped_default布尔值,如果不希望键入默认值,请设置True
  3. 示例
    import re
    from ciscoconfparse import CiscoConfParse
    from ciscoconfparse.ccp_util import IPv4Obj
    config = ['!','interface Serial1/0',' ip address 1.1.1.1 255.255.255.252','!','interface Serial2/0',' ip address 1.1.1.5 255.255.255.252','!',]
    parse = CiscoConfParse(config)
    INTF_RE = re.compile(r'interface\s\S+')
    ADDR_RE = re.compile(r'ip\saddress\s(\S+\s+\S+)')
    for obj in parse.find_objects(INTF_RE):print("{} {}".format(obj.text, obj.re_match_iter_typed(ADDR_RE, result_type=IPv4Obj)))
    
  4. 示例输出
    interface Serial1/0 <IPv4Obj 1.1.1.1/30>
    interface Serial2/0 <IPv4Obj 1.1.1.5/30>
    

re_match_typed

  1. 语法
    re_match_typed(regex, group=1, untyped_default=False, result_type=<class 'str'>, default='')
    
  2. 选项
    选项类型说明
    regexstr字符串或python正则表达式,应该匹配。此正则表达式应包含括号,括号用于绑定匹配组
    groupint一个整数,指定要返回的所需正则表达式组。组默认为1。
    result_typetype一种类型(通常是str、int、float或IPv4Obj中的一种)。所有返回值都转换为结果类型,默认为str.
    defaultany如果不匹配,则返回默认值
    untyped_defaultbool如果不希望键入默认值,请设置True
    返回结果result_type正则表达式组匹配的文本;如果不匹配,则返回默认值。除非untyped\u default为True,否则所有值都转换为结果类型
  3. 示例
    1. 见实例"将接口名称和槽位建立关联"

re_search 使用regex搜索此IOSCfgLine的文本

  1. 语法
    re_search(regex, default='')
    
  2. 选项
    选项类型说明
    regexstr字符串或python正则表达式,应该匹配。
    defaultstr如果在查找regex时re\u search()未找到匹配项,则返回的值
    返回结果str匹配的IOSCfgLine文本。如果不匹配,则返回默认值
  3. 示例

re_search_children 使用regex搜索此子级中包含的文本

  1. 介绍
    1. 使用regex搜索此子级中包含的文本
  2. 语法
    re_search_children(regex, recurse=False)
    
  3. 选项
    选项类型说明
    regexstr字符串或python正则表达式
    recursebool如果要搜索所有子级(子级、孙子级、曾孙级等),请设置为True
    返回结果list匹配的IOSCfgLine对象的列表。如果没有匹配项,则返回空list()
  4. 示例
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface Serial1/0',' ip address 1.1.1.1 255.255.255.252','!','interface Serial2/0',' ip address 1.1.1.5 255.255.255.252','!',]
    parse = CiscoConfParse(config)   
    interfaces = parse.re_search_children(regex=r'^interface\s(\S+)', recurse=False)
    print(interfaces)
    
  5. 示例输出
    [<IOSCfgLine # 1 'interface Serial1/0'>, <IOSCfgLine # 4 'interface Serial2/0'>]
    

实例

获取所有接口(interface)

  1. 获取的是对象
  2. 每个接口名称使用.text属性
  3. 可基于interfaces的索引获取指定接口,获取的也是对象,接口名称是"对象.text"
  4. 代码
    # 获取所有接口
    interfaces = cisco_cfg.find_objects("^interface")
    # 打印索引值为3的接口(对象),接口名使用"对象.text"
    print(interfaces[3])
    # 打印所有接口名称
    for obj in interfaces:print(obj.text)
    

获取包含特定配置的父配置

  1. 获取no shutdown的接口
  2. 方法一效率更高
    1. 方法一
      interfaces_All = cisco_cfg.find_objects(r"^interf")
      interfaces_AdminUp = list()
      for obj in interfaces_All:if obj.re_search_children(r"no shutdown"):interfaces_AdminUp.append(obj)
      print(interfaces_AdminUp)
      
    2. 方法二
      interface_NoShutdown = cisco_cfg.find_parents_w_child("^interface", "no shutdown")
      for i in interface_NoShutdown:print (i)
      

将接口名称和槽位建立关联

  1. 名称将转换为str(),槽将转换为int()
  2. 代码
    from ciscoconfparse import CiscoConfParse
    config = ['!','interface Serial1/0',' ip address 1.1.1.1 255.255.255.252','!','interface Serial2/0',' ip address 1.1.1.5 255.255.255.252','!',]
    parse = CiscoConfParse(config)   
    slots = dict()
    for obj in parse.find_objects(r'^interface'):name = obj.re_match_typed(regex=r'^interface\s(\S+)',default='UNKNOWN')slot = obj.re_match_typed(regex=r'Serial(\d+)',result_type=int,default=-1)print("Interface {0} is in slot {1}".format(name, slot))
    

获取接口名称和接口描述

  1. 代码
    parse = CiscoConfParse(file1)
    for obj in parse.find_objects_w_child(parentspec=r"^interface", childspec=r"descript"):name = obj.textdesc = obj.re_match_iter_typed(r'description\s(.*)', result_type=str)print(name,desc)
    

获取接口名称和IPv4地址

  1. 支持同一接口下有多个IPv4地址
  2. 代码
    from pathlib import Path
    from netaddr import IPNetwork
    from ciscoconfparse import CiscoConfParsefile = Path('/mnt/share/00temp/01_DongHuan/config/核心交换机.txt')
    #file = Path('/mnt/share/00temp/01_DongHuan/config/A508-xi-2.log')
    parse = CiscoConfParse(file)
    # 使用ip address 192.168.1.1/24格式的正则
    REGEX_ip1 = r'ip\s+address\s+(\S+/\d{1,2})'
    # 使用ip address 192.168.1.1 255.255.255.0格式的正则
    REGEX_ip2 = r'ip\s+address\s+(\S+[\s]\d+\S+)'
    # interface的正则
    REGEX_interface = r'^interface\s+(\S+)'
    for intf_obj in parse.find_objects(REGEX_interface):interface_name = intf_obj.text.replace('interface ','')# 每个元素为一个IP地址IPv4s = list()for child_obj in intf_obj.children:  # Iterate over intf children#print(child_obj.text)if '/' in child_obj.text:REGEX_ip = REGEX_ip1else:REGEX_ip = REGEX_ip2ipv4 = child_obj.re_match_typed(REGEX_ip)if ipv4:if " " in ipv4:ipv4 = ipv4.split()ipv4 = IPNetwork(f'{ipv4[0]}/{ipv4[1]}')IPv4s.append(str(ipv4))if IPv4s:# 显示接口有IPv4地址的接口名称,和IPv4(逗号分隔的ipv4地址)print(interface_name,','.join(IPv4s))
    
http://www.lryc.cn/news/340483.html

相关文章:

  • HDFS详解(Hadoop)
  • python创建word文档并向word中写数据
  • MongoDB的安装配置及使用
  • Go学习路线
  • 安全大脑与盲人摸象
  • 如何使用Git-Secrets防止将敏感信息意外上传至Git库
  • Day 14 网络协议
  • msyql中SQL 错误 [1118] [42000]: Row size too large (> 8126)
  • 实验六 智能手机互联网程序设计(微信程序方向)实验报告
  • Linux环境下,让Jar项目多线程部署成为可能
  • k8s调度场景
  • 基于小程序实现的餐饮外卖系统
  • 家居网购项目(手写分页)
  • goland2024安装包(亲测可用)
  • 35、链表-LRU缓存
  • 数据结构速成--栈
  • 算法练习第15天|226.翻转二叉树
  • C#面向对象——封装、封装案例示例
  • 【InternLM 实战营第二期-笔记3】茴香豆:搭建你的 RAG 智能助理
  • Advanced RAG 03:运用 RAGAs 与 LlamaIndex 评估 RAG 应用
  • leetcode
  • Unity DOTS《群体战斗弹幕游戏》核心技术分析之3D角色动画
  • react异步组件如何定义使用 标准使用方法
  • React + Ts + Vite + Antd 项目搭建
  • js爬虫puppeteer库 解决网页动态渲染无法爬取
  • 代码随想录:二叉树5
  • Tomcat 获取客户端真实IP X-Forwarded-For
  • 记录PS学习查漏补缺
  • Kafka 架构深入探索
  • k-means聚类算法的MATLAB实现及可视化