我已经实现了一个连接到Cisco设备并收集show run输出的脚本。
脚本是:
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
问题
有没有办法更改脚本以便逐行显示输出?
答案 0 :(得分:0)
documentation for telnetlib对Telnet.read_very_eager
并不是很清楚,但它提到它为其他方法读写bytes
。 type(s)
可能是bytes
。
使用bytes.decode
获取字符串:print(s.decode('ascii'))
(使用适当的编码)
注意:这适用于Python 3。
答案 1 :(得分:-1)
你需要检查字符串,使用一些常见的特殊字符,使用python split()函数分隔行,然后启动一个带有变量长度的for循环,然后打印。