Extract specific string from Telnet output with Python
Question: 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 "?


Answer: A simple way is to use regular expressions and search for the hostname in your
variable. To match the hostname you could use this regex pattern:

`hostname (?P<hostname>\w+)`

The code in python would look like:

    
    
    import re
    p = re.compile(ur'hostname (?P<hostname>\w+)')
    test_str = u"Current configuration : 1543 bytes\n\n!\nversion 12.4\nservice timestamps debug datetime msec\nservice timestamps log datetime msec\nno service password-encryption\n!\nhostname ESW1\n!\nboot-start-marker\nboot-end-marker\n!"
    
    hostnames = re.findall(p, test_str)
    print(hostnames[0])
    

The result is: `ESW1`

Try it out on [regex101](https://regex101.com/r/nX9qB7/1)

