我正在尝试从另一台远程设备远程登录到远程设备,使用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()
答案 0 :(得分:0)
您没有在代码中进行嵌套连接。您只是从localhost连接到两台不同的计算机,但显然您实际上无法连接到第二台计算机。要对第二个主机执行嵌套的Telnet,您必须告诉第一个telnet到第二个主机:使用
替换tn2 = telnetlib.Telnet("secondDevice")
tn.write("telnet secondDevice\n")
由于您有嵌套连接,因此您的所有localhost都应该看到tn
。你可以完全摆脱tn2
对象。与第二个设备的所有交互都将通过向第一个设备发送字符串来完成,第一个设备位于连接到第二个设备的会话中。