【问题标题】:Python telnet connection closesPython telnet 连接关闭
【发布时间】:2019-07-11 23:12:36
【问题描述】:

我正在尝试通过 telnet 向服务器发送一些命令。这已经手动完成了很多次,但我被要求使用 python 自动化它。

我的代码是这样开始的:

import telnetlib

HOST = "xxx.xxx.xxx.xxx"
PORT = xx

print("connecting...")
tn = telnetlib.Telnet(HOST, PORT)
tn.read_until(b"250")
print("connection established!\nsending ehlo...")
tn.write(b"EHLO test.com")
tn.read_until(b"250")
print("response received")
...

如果我手动输入命令,它会起作用。但是脚本在几分钟后中止,输出如下:

connecting...
connection established!
sending ehlo...
Traceback (most recent call last):
  File "telnet_test.py", line 11, in <module>
    tn.read_until(b"250")
  File "/usr/lib/python3.6/telnetlib.py", line 327, in read_until
    return self.read_very_lazy()
  File "/usr/lib/python3.6/telnetlib.py", line 403, in read_very_lazy
    raise EOFError('telnet connection closed')
EOFError: telnet connection closed

根据输出,我的 telnet 连接已关闭,但我不明白为什么!? 可能很重要:启动后输出会显示connecting... 几分钟,然后会打印包括异常在内的其余输出。 read_until() 函数阻塞的时间是否超过了必要的时间,所以我的连接超时了?我该如何解决这个问题?

【问题讨论】:

  • 我相信您需要在每个命令之后发送一个换行符,至少在您尝试与 SMTP 服务器通信时。 (服务器可能正在超时,因为您从未发送过完整的命令。)
  • 您可以尝试 set_debuglevel() 以获得更多反馈。此外,您可能会遍历 read_some() 以了解连接发生了什么。

标签: python connection timeout telnet telnetlib


【解决方案1】:

感谢用户 molbdnilo

我需要在每个命令上添加一个换行符。

所以tn.write(b"EHLO test.com") 变成了tn.write(b"EHLO test.com\n")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 2011-05-30
    • 2012-11-19
    • 2011-12-07
    • 2011-05-04
    • 2019-01-07
    • 2017-12-20
    相关资源
    最近更新 更多