【发布时间】:2021-10-08 00:43:56
【问题描述】:
我正在尝试仅使用 telnetlib 从多个设备收集 show tech-support。它适用于一个小问题。它收集show tech-support 命令的完整输出并将其导出到一个文本文件(export_text_support() 是一个简单的with open() 语句)。
我实验室中两个开关的全部输出是show tech-support 命令的32,768 和16,325 行。我得到了整个输出,BUT 一个小问题是会话在完成后没有退出调用tn.write(b"exit\n")。当exec-timeout 按下开关(会话变为空闲时) 时,它会退出,这两个开关都是 10 分钟,而不是当没有其他内容可从 tn 读取时。 p>
我尝试了以下相同的代码来获得较短的输出,例如 show running-config,我在导出的文件中看到了 #exit(末尾有一个空行)。
短输出
...
365 !
366 end
367
368 Switch#
369 Switch#exit
370
巨大的输出
....
16321 423 entries printed
16322
16323
16324
16325 Switch#
(你可以注意到exit在巨大的输出样本中没有看到,最后也没有空行)
这是我的sn-p
from telnetlib import Telnet
host = ""
username = ""
password = ""
def get_tech_support(host: str) -> None:
with Telnet(host=host, port=23) as tn:
# Check for credentials
if username:
tn.read_until(b"Username: ")
tn.write(username.encode("ascii") + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode("ascii") + b"\n")
# Some commands
commands = ["\n", "terminal width 115", "terminal length 0"]
[tn.write(command.encode("ascii") + b"\n") for command in commands]
# The main command
cmd = "show tech-support"
# Send the main command
tn.write(cmd.encode("ascii") + b"\n")
hostname = tn.read_until(b"#")
tn.write(b"\nexit\n")
command_output = tn.read_all().decode("ascii")
result = dict(
ip=host, hostname=hostname, command=cmd, command_output=command_output
)
export_tech_support(command_output=result) # Export the show command output
如何让会话在完成详细输出后自动退出并避免等待exec-timeout 被点击(在我的情况下为 10 分钟)
【问题讨论】:
标签: python paramiko cisco telnetlib netmiko