简体   繁体   English

从Telnet会话内部进行Telnet(Python)

[英]Telnet from inside a telnet session (Python)

I am trying to telnet to a remote device from another remote device, doing a nested telnet using telnetlib. 我试图从另一个远程设备远程登录到远程设备,使用telnetlib进行嵌套的telnet。 While I can easily communicate with the first device, I am not able to get the output from the second device. 虽然我可以轻松地与第一台设备通信,但是我无法从第二台设备获取输出。 Below is my code, am I doing this correctly? 以下是我的代码,我可以正确执行此操作吗?

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()

Edit 1 编辑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()

You are not doing a nested connection in your code. 您没有在代码中进行嵌套连接。 You are just connecting to two different computers from localhost, but apparently you can not actually connect to the second one. 您只是从本地主机连接到两台不同的计算机,但是显然您实际上无法连接到第二台计算机。 To do a nested Telnet to the second host, you have to tell the first one to telnet to the second one: replace tn2 = telnetlib.Telnet("secondDevice") with 要对第二个主机执行嵌套的Telnet,必须告诉第一个主机telnet到第二个主机:将tn2 = telnetlib.Telnet("secondDevice")替换为

tn.write("telnet secondDevice\n")

Since you have a nested connection, all your localhost should see is tn . 由于您具有嵌套连接,因此所有本地主机应该看到的是tn You can get rid of the tn2 object entirely. 您可以完全摆脱tn2对象。 All interaction with the second device will be done by sending strings to the first device, which is in a session connected to the second device. 与第二设备的所有交互将通过向第一设备发送字符串来完成,该字符串位于连接到第二设备的会话中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM