我试图从另一个远程设备向远程设备发送telnet,使用telnetlib进行嵌套的telnet操作。虽然我可以很容易地与第一个设备通信,但我无法从第二个设备获得输出。下面是我的代码,我做得对吗?
import telnetlib
HOST = "firstDevice"
user = "lab"
password = "lab"
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
#Nested telnet
tn2 = telnetlib.Telnet("secondDevice")
tn2.read_until("#")
tn2.write("sh clock\n")
#Close tn2
tn2.write("exit\n")
print tn2.read_all()
#Close tn
tn.write("exit\n")
print tn.read_all()编辑1
import telnetlib
HOST = "firstDevice"
user = "lab"
password = "lab"
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
#Nested telnet
tn.write("telnet secondDevice\n")
tn.write("sh clock\n")
#Close nested session
tn.write("exit\n")
#Close tn
tn.write("exit\n")
print tn.read_all()发布于 2015-11-30 18:26:09
您没有在代码中执行嵌套连接。您只是从本地主机连接到两台不同的计算机,但显然无法连接到第二台计算机。要对第二个主机执行嵌套的Telnet,您必须告诉第一个主机到第二个主机:将tn2 = telnetlib.Telnet("secondDevice")替换为
tn.write("telnet secondDevice\n")由于您有一个嵌套的连接,您的本地主机应该看到的全部是tn。您可以完全摆脱tn2对象。与第二设备的所有交互将通过向第一设备发送字符串来完成,第一设备位于连接到第二设备的会话中。
https://stackoverflow.com/questions/34005230
复制相似问题