Search code examples
pythonregexnetwork-programmingautomation

Python find value in text string


I am building a network automation script in python, and I got into a problem that I don't know how to resolve. I have the following output

CPE-MGT {
    instance-type virtual-router;
    interface ge-0/0/0.0;
    routing-options {
        static {
            route 192.168.253.115/32 next-hop 192.168.100.1;
            route 0.0.0.0/0 next-hop 192.168.100.1;
        }
    }
}
DATA {
    instance-type virtual-router;
    interface ge-0/0/1.0;
}
MGMT_BK {
    instance-type virtual-router;
    interface ge-0/0/2.0;
    routing-options {
        static {
            route 192.168.253.115/32 next-hop 192.168.100.1;
            route 0.0.0.0/0 next-hop 192.168.100.1;
        }
    }
}

I need to obtain the name of there I find the name of specific primary key interfaces; perhaps it will be clearer if I give an example.

I have a regex that looks into the text and finds that ge-0/0/0.0 is in the text now; what I don't know is how to obtain CPE-MGT.

cmd = net_connect.send_command(
        juniper_cmds["sh_routing_instance"])
    logger.debug(f'{ip_dict[config_dict["csv_ip_colum"]][ips]}:Device routing instances {cmd}')
    regex_routing_instance = re.compile(f'{interface[0]}')
    routing_instance = regex_routing_instance.findall(cmd)```

Solution

  • You could use two patterns and the regex module which offers recursion:

    import regex as re
    
    data = """
    CPE-MGT {
        instance-type virtual-router;
        interface ge-0/0/0.0;
        routing-options {
            static {
                route 192.168.253.115/32 next-hop 192.168.100.1;
                route 0.0.0.0/0 next-hop 192.168.100.1;
            }
        }
    }
    DATA {
        instance-type virtual-router;
        interface ge-0/0/1.0;
    }
    MGMT_BK {
        instance-type virtual-router;
        interface ge-0/0/2.0;
        routing-options {
            static {
                route 192.168.253.115/32 next-hop 192.168.100.1;
                route 0.0.0.0/0 next-hop 192.168.100.1;
            }
        }
    }
    """
    
    rx_block = re.compile(r"""
        ^(?P<name>[A-Z_-]+)\s+
        (?P<body>\{
            (?:(?:[^{}]+)|(?2))+
        \})
    """, re.M | re.X)
    
    rx_inner = re.compile(r"interface ge-0/0/0.0;")
    
    for block in rx_block.finditer(data):
        m = rx_inner.search(block.group('body'))
        if m:
            print(block.group('name'))
    

    This would yield

    CPE-MGT
    

    Two notes here: you wouldn't really need a regular expression for the inner search as it is a static string and two - probably use a parser solution instead.
    See a demo for the expression on regex101.com.