使用 Python 从 Telnet 输出中提取特定字符串

Extract specific string from Telnet output with Python

我正在尝试编写一个 Python 脚本来远程登录到一组 Cisco 路由器,提取 运行 配置并保存。每个路由器都有不同的名称,所以我想做的是提取设备名称并使用该名称保存输出文件。例如,这是一段 Cisco 路由器输出,其中有一行 "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
!

我正在使用 telnetlib,我可以获得输出并将其保存在一个变量中。我的问题是如何识别该特定行并在 "hostname " 之后提取 "ESW1" 字符串?

一种简单的方法是使用正则表达式并在变量中搜索主机名。要匹配主机名,您可以使用此正则表达式模式:

hostname (?P<hostname>\w+)

python 中的代码如下所示:

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])

结果是:ESW1

regex101

上试用

使用正则表达式:

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

或者,如果您不喜欢正则表达式:

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

我认为正则表达式 运行 比循环更快。

>>> 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']
>>>