La entrada se ve a continuación y quiero que la salida sea la primera interfaz donde status = [up]: en este ejemplo a continuación, la salida debería ser Ethernet1 / 48

Last bundled member is Ethernet1/48
Ports:   Ethernet1/45    [active ] [down]
         Ethernet1/46    [active ] [down]
         Ethernet1/47    [active ] [down] *
         Ethernet1/48    [active ] [up]
         Ethernet2/1/1   [active ] [up]
         Ethernet2/1/2   [active ] [up]
         Ethernet2/1/3   [active ] [up]
         Ethernet2/1/4   [active ] [up]
-1
ferjani nasraoui 28 feb. 2018 a las 23:28

3 respuestas

La mejor respuesta

Creo que lo tengo, este código funcionó:

import re

text = """
Last bundled member is Ethernet1/48
Ports:   Ethernet1/45    [active ] [down]
         Ethernet1/46    [active ] [up]
         Ethernet1/47    [active ] [up] *
         Ethernet1/48    [active ] [up]
         Ethernet2/1/1   [active ] [up]
         Ethernet2/1/2   [active ] [up]
         Ethernet2/1/3   [active ] [up]
         Ethernet2/1/4   [active ] [up]
"""


pattern = '\w+\S+(?=\s*\[\w+ \] \[up\])'
result = re.findall(pattern, text, re.MULTILINE)
print result[0].strip()

He editado el patrón para que coincida con otras salidas posibles como: si [up] era la primera línea, el patrón antiguo también coincidiría con los puertos: word si el protocolo utilizado no fuera LACP, la salida sería [on] [up] y no [ activo] [arriba].

Gracias

2
ferjani nasraoui 1 mar. 2018 a las 00:48

Esto funcionó

CÓDIGO

test_str = '''
    Last bundled member is Ethernet1/48\n
    Ports:   Ethernet1/45    [active ] [down]\n
             Ethernet1/46    [active ] [down]\n
             Ethernet1/47    [active ] [down] *\n
             Ethernet1/48    [active ] [up]\n
             Ethernet2/1/1   [active ] [up]\n
             Ethernet2/1/2   [active ] [up]\n
             Ethernet2/1/3   [active ] [up]\n
             Ethernet2/1/4   [active ] [up]
             '''

for line in test_str.split('\n'):
    if '[up]' in line:
        tmp_line = line.split(' ')

        flag = False

        for word in tmp_line:
            if word:
                print(word)
                flag=True
                break

        if flag:
            break

SALIDA

Ethernet1/48
0
Mohsin Bukhari 28 feb. 2018 a las 20:52

Usted podría usar

import re

string = """
Last bundled member is Ethernet1/48
Ports:   Ethernet1/45    [active ] [down]
         Ethernet1/46    [active ] [down]
         Ethernet1/47    [active ] [down] *
         Ethernet1/48    [active ] [up]
         Ethernet2/1/1   [active ] [up]
         Ethernet2/1/2   [active ] [up]
         Ethernet2/1/3   [active ] [up]
         Ethernet2/1/4   [active ] [up]
"""

rx = re.compile(r'Ethernet\S+(?=\s*\[active \] \[up\])')
match = rx.search(string)
if match:
    print(match.group(0))

Lo que produce

Ethernet1/48
1
Jan 28 feb. 2018 a las 22:14