Python telnet 连接关闭

Python telnet connection closes

我正在尝试通过 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() 函数阻塞的时间是否超过必要的时间,所以我的连接超时?我该如何解决这个问题?

感谢用户 molbdnilo

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

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