我遇到了同样的问题。
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