簡體   English   中英

使用 Python 從 Telnet 輸出中提取特定字符串

[英]Extract specific string from Telnet output with Python

我正在嘗試編寫一個 Python 腳本來 telnet 到一堆 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

我認為正則表達式會比循環運行得更快。

一種簡單的方法是使用正則表達式並在變量中搜索主機名。 要匹配主機名,您可以使用此正則表達式模式:

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試試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM