Fanttazio
Fanttazio

Reputation: 27

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 "?

Upvotes: 2

Views: 1593

Answers (3)

mhawke
mhawke

Reputation: 87134

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.

Upvotes: 1

Sdwdaw
Sdwdaw

Reputation: 1037

>>> import re
>>> telnetString = """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
... !"""
... 
>>> re.findall(r'hostname (.*?)\n',telnetString)
['ESW1']
>>> 

Upvotes: 0

cansik
cansik

Reputation: 2004

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

Upvotes: 0

Related Questions