1

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?

  • 1
    I believe you need to send a newline after each command, at least if you're trying to talk to an SMTP server. (The server is probably timing out because you never sent a complete command.) – molbdnilo Feb 18 '19 at 14:44
  • You might try set_debuglevel() to get additional feedback. Also, you might loop over read_some() in order to find out what's happening with the connection. – seayak Feb 18 '19 at 14:46

1 Answers1

1

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