我正在尝试使用telnetlib从cisco路由器读取
import telnetlib
tn = telnetlib.Telnet(’10.106.218.50’, 17280)
cmd1=”enable”
cmd2=”show run”
#session.write("command".encode('ascii') + b"\r")
tn.write(cmd1.encode('ascii') + b"\r")
tn.write(cmd2.encode('ascii') + b"\r")
#op=tn.read_very_eager()
#op=tn.read_some()
#op=tn.read_until('#')
op=tn.read_all()
print op
我能够成功写入路由器的控制台 然而,当我尝试从路由器的控制台读取时,系统只是挂起。 当我使用read_some()时,我得到输出的一部分。但是read_all()只是挂起而没有给出任何响应 请提出解决方案
答案 0 :(得分:1)
read_all()
如果在建立连接时没有指定超时,则python< telnetlib模块中的命令将阻止。
您的调用命令应该看起来像
tn = telnetlib.Telnet('10.106.218.50', 17280, timeout = 1)
您也可以替换自己的超时值。
答案 1 :(得分:0)
我遇到了同样的问题。
import socket, telnetlib
def telnet(ip_address,user_name,password):
tn = telnetlib.Telnet(ip_address,23,1)
# tn.set_debuglevel(2)
tn.write(user_name + '\n')
tn.write(password + '\n')
tn.write('show version\n')
tn.write('show power\n')
print tn.read_all()
tn.close()
telnet('10.236.0.19','who','who')
错误日志在这里是相同的:
Traceback (most recent call last):
File "telnet.py", line 41, in <module>
telnet('10.236.0.19','who','who')
File "telnet_tn.py", line 23, in telnet
print tn.read_all()
File "C:\Python27\lib\telnetlib.py", line 385, in read_all
self.fill_rawq()
File "C:\Python27\lib\telnetlib.py", line 576, in fill_rawq
buf = self.sock.recv(50)
socket.timeout: timed out
然后我尝试在C:\ Python27 \ lib \ telnetlib.py中修改函数read_all()。之后,它就达到了我的期望。您可以尝试一下。
之前:
def read_all(self):
"""Read all data until EOF; block until connection closed."""
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
之后(为socket.timeout添加一个例外):
def read_all(self):
"""Read all data until EOF; block until connection closed."""
self.process_rawq()
while not self.eof:
try:
self.fill_rawq()
self.process_rawq()
except:
break
buf = self.cookedq
self.cookedq = ''
return buf
答案 2 :(得分:0)
对我来说,解决方案是使用tn.red_until()。该代码对我有用。 而且,如果您不需要将输出发送到文本文件,请修改:
data = data + tn.read_until(b"FIN\n", timeout = TIMEOUT).decode('ascii')
作者:
tn.read_until(b"FIN\n", timeout = TIMEOUT)
这是我的代码:
import sys
import telnetlib
import time
username = "admin"
password = "admin"
command = "show version"
TIMEOUT = 3
router_list = open("hostlist.txt")
for line in router_list:
tn = telnetlib.Telnet(line.rstrip())
tn.set_debuglevel(1)
time.sleep(2)
data = data + tn.read_until(b"Username: ").decode('ascii')
tn.write(username.encode('ascii') + b"\n")
time.sleep(2)
data = data + tn.read_until(b"Password: ").decode('ascii')
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(command.encode('ascii') + b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"echo FIN\n")
time.sleep(2)
data = data + tn.read_until(b"FIN\n", timeout = TIMEOUT).decode('ascii')
print("Imprimiendo:" + data)
op=open ("output.txt", "a").write(data)
tn.close()