如何逐行打印 telnet 输出?

How can i get telnet output printed line by line?

我已经实现了一个连接到 Cisco 设备并收集 show 运行 输出的脚本。

脚本是:

import getpass
import telnetlib
import time


HOST = "10.62.149.9"
user = input("Enter your remote account: ")
password = getpass.getpass("User Password: ")
enable = getpass.getpass("Enable Password: ")

tn = telnetlib.Telnet(HOST)

tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b"\n")
tn.write(b"enable\n")
if enable:
    tn.read_until(b"Password: ")
    tn.write(enable.encode('ascii') + b"\n")
tn.write(b"term len 0\n")
tn.write(b"show run\n")
time.sleep(10)
s = tn.read_very_eager()
print (s)
tn.close()

脚本输出为:

\r\ninterface GigabitEthernet1/0/26\r\n!\r\ninterface GigabitEthernet1/0/27\r\n!\r\ninterface GigabitEthernet1/0/28\r\n!\r\ninterface GigabitEthernet1/0/29\r\n!\r\ninterface GigabitEthernet1/0/30\r\n!\r\ninterface GigabitEthernet1/0/31\r\n!\r\ninterface GigabitEthernet1/0/32\r\n!\r\ninterface GigabitEthernet1/0/33\r\n!\r\ninterface GigabitEthernet1/0/34\r\n!\r\ninterface GigabitEthernet1/0/35\r\n!\r\ninterface GigabitEthernet1/0/36\r\n!\r\ninterface GigabitEthernet1/0/37\r\n!\r\ninterface GigabitEthernet1/0/38\r\n!\r\ninterface GigabitEthernet1/0/39\r\n!\r\ninterface GigabitEthernet1/0/40\r\n!\r\ninterface GigabitEthernet1/0/41\r\n!\r\ninterface GigabitEthernet1/0/42\r\n!\r\ninterface GigabitEthernet1/0/43\r\n!\r\ninterface GigabitEthernet1/0/44\r\n!\r\ninterface GigabitEthernet1/0/45\r\n!\r\ninterface GigabitEthernet1/0/46\r\n!\r\ninterface GigabitEthernet1/0/47\r\n!\r\ninterface GigabitEthernet1/0/48\r\n no switchport\r\n ip address 10.62.149.9
255.255.255.128\r\n!\r\ninterface GigabitEthernet1/0/49\r\n!\r\ninterface GigabitEthernet1/0/50\r\n!\r\ninterface GigabitEthernet1/0/51\r\n!\r\ninterface GigabitEthernet1/0/52\r\n!\r\ninterface Vlan1\r\n no ip address\r\n shutdown\r\n!\r\ninterface Vlan10\r\n ip address 10.10.10.1
255.255.255.0\r\n!\r\ninterface Vlan199\r\n ip address 217.21.0.6 255.255.254.0\r\n no ip redirects\r\n ip ospf priority 100\r\n!\r\ninterface Vlan777\r\n ip address 7.7.7.1

问题

有没有办法更改脚本以便逐行显示输出?

您需要使用 python split() 函数检查带有分隔行的一些常见特殊字符的字符串,然后使用变量的长度启动 for 循环,然后打印。

documentation for telnetlib中对Telnet.read_very_eager不是很清楚,但它提到它读写bytes用于其他方法。 type(s) 大概是 bytes.

使用bytes.decode得到一个字符串:print(s.decode('ascii'))(使用适当的编码)

注意:这是针对 Python 3.