0

我正在尝试解释开关的以下输出。基本上我希望它通过输出直到找到“notconnect”然后将接口的名称存储在一个数组中。然后继续通过文件并将下一个“notconnect”接口存储为数组中的下一个元素。以下示例中的接口为 Gi1/0/4。我只是不确定从哪里开始。任何帮助,将不胜感激。我正在使用 Python 3.3.2。

b'\r\n\r\nMS-2673-DC-CS01#terminal length 0\r\nMS-2673-DC-CS01#sh interface status\r\n\r\nPort      Name               Status       Vlan       Duplex  Speed Type\r\nGi1/0/1   Connection to MS-2 connected    trunk      a-full a-1000 1000BaseSX SFP\r\nGi1/0/2   Connection to MS-2 connected    trunk      a-full a-1000 1000BaseSX SFP\r\nGi1/0/3   Connection to MS-2 connected    trunk      a-full a-1000 1000BaseSX SFP\r\nGi1/0/4                      notconnect   trunk        auto   auto Not Present\r\nGi1/0/5   Connection to MS-2 connected    trunk      a-full a-1000 1000BaseSX SFP\r\nGi1/0/6   Connection to MS-2 connected    trunk      a-full a-1000 10/100/1000BaseTX SFP\r\nGi1/0/7   Connection to MS-2 connected    trunk      a-full a-1000 10/100/1000BaseTX SFP\r\nGi1/0/8   Connection to MS-2 connected    trunk      a-full a-1000 10/100/1000BaseTX SFP\r\nGi1/0/9   Connection to MS-2 connected    trunk      a-full a-1000 10/100/1000BaseTX SFP\r\nGi1/0/10  Connection to MS-2 connected    trunk      a-full a-1000 10/100/1000BaseTX SFP\r\nGi1/0/11  Connection to MS-2 connected    trunk      a-full a-1000 10/100/1000BaseTX SFP\r\nGi1/0/12  Connection Server  connected    32         a-full a-1000 10/100/1000BaseTX SFP\r\nMS-2673-DC-CS01#exit\r\n'
4

1 回答 1

0

首先,您必须弄清楚格式什么。然后你可以编写代码来解析它。

显然,这是一种固定宽度的列格式。接口总是在前 10 个字符中,连接字符串在接下来的 20 个字符中,等等。所以,给定一行:

components = (line[:10], line[10:29], line[29:42], line[42:53], line[53:60],
              line[60:67], line[67:])

... 将获得列。

因此,只需遍历这些行,将每一行拆分为列,然后找到正确的行:

def parse_log(log)
    for line in log.splitlines():
        if line[29:42].rstrip() == 'notconnect':
            yield line[:10].rstrip()

notconnect_interfaces = list(parse_log(log))

如果您想要更通用的东西,只需编写一个列拆分函数,该函数采用一行和一系列列边界。

def parse_line(line, columns):
    for start, stop in zip(columns, columns[1:])
        yield line[start, stop].rstrip()

def parse_log(log):
    for line in log.splitlines():
        yield list(parse_line(line, (0, 10, 29, 42, 53, 60, 67, 80)))

def find_notconnected(log):
    for port, name, status, vlan, duplex, speed, type in parse_log(log):
        if status == 'notconnect':
            yield port

您也可以将其转换为一系列 genexpr 而不是一组函数。更简洁一点,但可能不那么可读:

bounds = (0, 10, 29, 42, 53, 60, 67, 80)
columns = ([line[start:stop].rstrip() for start, stop in zip(bounds, bounds[1:])]
           for line in log.splitlines())
notconnected = (port for port, _, status, _, _, _, _ in columns 
                if status == 'notconnected')
于 2013-10-09T18:49:56.133 回答