Search code examples
pythontelnet

Extract specific string from Telnet output with Python


I'm trying to write a Python script to telnet to a bunch of Cisco routers, extract the running configuration and save it. Each router has a different name so what I would like to do is to extract the device name and save the output file with that name. For example this a snippet of a Cisco router output where there is a line "hostname ESW1":

Current configuration : 1543 bytes

!
version 12.4
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
!
hostname ESW1
!
boot-start-marker
boot-end-marker
!

I'm using telnetlib and I can get the output and save it in a variable. My question is how can I identify that specific line and extract the "ESW1" string after the "hostname "?


Solution

  • Use a regular expression:

    config_string = '''Current configuration : 1543 bytes
    
    !
    version 12.4
    service timestamps debug datetime msec
    service timestamps log datetime msec
    no service password-encryption
    !
    hostname ESW1
    !
    boot-start-marker
    boot-end-marker
    !'''
    
    import re
    hostname = re.findall(r'hostname\s+(\S*)', config_string)[0]
    print hostname
    # ESW1
    

    Or, if you don't like regular expressions:

    for line in config_string.splitlines():
        if line.startswith('hostname'):
        hostname = line.split()[1]
    print hostname
    # ESW1
    

    I think that the regex will run faster than the loop.