Skip to main content
 首页 » 编程设计

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

2025年05月04日15powertoolsteam

我正在尝试编写一个 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,我可以获得输出并将其保存在一个变量中。我的问题是如何识别该特定行并在“主机名”之后提取“ESW1”字符串?

请您参考如下方法:

使用正则表达式:

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 

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