简体   繁体   English

Python telnetlib客户端似乎没有打开到服务器的telnet连接

[英]Python telnetlib client doesn't appear to be opening telnet connection to server

I am trying to open a telnet connection, write one string, then print everything from the telnet server in Python. 我试图打开一个telnet连接,写一个字符串,然后从Python中的telnet服务器打印所有内容。 I assume I am missing something obvious because the documentation seems pretty self-explanatory and doing what I think is the exact same thing in terminal works fine. 我假设我遗漏了一些明显的东西,因为文档看起来非常不言自明,我认为在终端中完全相同的工作正常。

Here is the Python code: 这是Python代码:

import telnetlib

telnet = telnetlib.Telnet()
telnet.open('192.168.1.128', 9801, 10)
telnet.write("SYSTEM_CAL")

print(telnet.read_all())

This times out after 10 seconds / doesn't successfully connect to the server I assume. 这个超时10秒后/没有成功连接到我假设的服务器。 Here is the output: 这是输出:

Traceback (most recent call last):
  File "/Volumes/Work/Scripting/Telnet Test/main.py", line 9, in <module>
    print(telnet.read_all())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/telnetlib.py", line 385, in read_all
    self.fill_rawq()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/telnetlib.py", line 576, in fill_rawq
    buf = self.sock.recv(50)
socket.timeout: timed out

In the image below I connect to the same server in terminal and everything works fine. 在下图中我连接到终端中的同一台服务器,一切正常。 At the end I give the "DISCONNECT" command taken by the server which is why the connection closes. 最后,我给出服务器采用的“DISCONNECT”命令,这就是连接关闭的原因。

连接到终端的Telnet服务器

Am I missing something? 我错过了什么吗? Why is this working in Terminal and not in Python? 为什么这在终端而不是在Python中工作?

I suppose you are sending your command too early, and the receiving end is ignoring it. 我想你太早发出你的命令,接收端却忽略了它。 Try to read the banner first: 首先尝试阅读横幅:

print(telnet.read_until("Welcome."))
telnet.write("SYSTEM_CAL")
print(telnet.read_all())

EDIT: 编辑:

I also note that you don't have a line-terminating sequence at the end of "SYSTEM_CAL". 我还注意到在“SYSTEM_CAL”末尾没有行终止序列。 I presume that, in the interactive session, you press ↵ ENTER after you type "SYSTEM_CAL". 我相信,在互动环节中,你按↵Enter键后,你输入“SYSTEM_CAL”。 If that is the case, you'll need to add \\n at the end of the write() call: 如果是这种情况,您需要在write()调用结束时添加\\n

telnet.write("SYSTEM_CAL\n")

Depending upon other factors outside of your question, it is possible that you may need one of the following instead: 根据您问题之外的其他因素,您可能需要以下其中一项:

telnet.write("SYSTEM_CAL\r")
telnet.write("SYSTEM_CAL\r\n")

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

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