I'm trying to send some commands via telnet to a server. This has been done by hand many times, but I was asked to automate it using python.
My code starts like this:
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")
...
If I enter the commands by hand, it works. But the script aborts after a few minutes with the following output:
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
According to the output my telnet connection got closed, but I can't see why!?
Maybe important: After launch the output says connecting...
for a few minutes, and then the rest of the output including the exception get's printed.
Is the read_until()
function blocking longer than necessary, so my connection timouts? And how do I solve this?
credits to user molbdnilo
I needed to add a newline character on every command.
So tn.write(b"EHLO test.com")
becomes tn.write(b"EHLO test.com\n")