如何解析和提取文件的端口模式?

2024-09-27 23:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下信息的文本文件:

interfaces {
ge-2/0/0 {
    description "site1;;hostname1;ge-16/0/9;;;TRUST;";
    unit 0 {
        family ethernet-switching {
            port-mode trunk;
        }
    }
}
ge-2/0/2 {
    description "site2;;hostname2;ge-16/0/8;;;TRUST;";
    unit 0 {
        family ethernet-switching {
            port-mode trunk;
        }
    }
}

在其他人的帮助下,我已经能够提取接口id(ge-2/0/0)以及描述

其代码如下:

from ciscoconfparse import CiscoConfParse
parse = CiscoConfParse("testconfig.txt", syntax="junos")

intfs = parse.find_objects_w_parents(r'^interfaces', r'^\s+ge-')
for intfobj in intfs:
    intf_name = intfobj.text.strip()
    descr = intfobj.re_match_iter_typed(r'description\s+"(\S.+?)"$', group=1)
    print ('Intf: {0}, {1}'.format(intf_name, descr))

这给了我一个结果:

Intf: ge-2/0/0, site1;;hostname1;ge-16/0/9;;;TRUST;
Intf: ge-2/0/2, site2;;hostname2;ge-16/0/8;;;TRUST;

到目前为止,这对我来说是巨大的,我真的认为我将能够弄清楚如何深入挖掘接口以提取“端口模式”

到目前为止我的努力都失败了

这是我试图挖掘这些信息的一般思路,但没有结果:

ltype = parse.find_objects_w_parents(r'^interfaces', r'^\s+ge-', r'^unit\s0', r'^family\sethernet-switching')
for ltypeobj in ltype:
    pmode = intfobj.re_match_iter_typed(r'port-mode\s+"(\S.+?)"$', group=1)
    print ('Port Mode: {0}'.format(pmode))

我明白了,我就是想不通

Traceback (most recent call last):
  File "convert.py", line 11, in <module>
    ltype = parse.find_objects_w_parents(r'^interfaces', r'^\s+ge-', r'^unit\s0', r'^family\sethernet-switching')
TypeError: find_objects_w_parents() takes from 3 to 4 positional arguments but 5 were given

如有任何建议,我们将不胜感激


Tags: inobjectsparseportmodeunitdescriptionfind
1条回答
网友
1楼 · 发布于 2024-09-27 23:23:36

检查这个例子是否适合你

import re
for i in re.findall('(ge-\d/\d/\d).*\n\s+description\s+(.*)(\n\s+.*){2}\n\s+port-mode\s(.*);', x):
    print 'interface: ', i[0]
    print 'description: ', i[1]
    print 'port mode: ', i[-1]

输出:

interface:  ge-2/0/0
description:  "site1;;hostname1;ge-16/0/9;;;TRUST;";
port mode:  trunk
interface:  ge-2/0/2
description:  "site2;;hostname2;ge-16/0/8;;;TRUST;";
port mode:  trunk

相关问题 更多 >

    热门问题