Why does piping commands into telnet result in intermittent connection failures?

0

As a cheap hack workaround on a number of servers that don't have the mail command, a script was written that echoes SMTP commands into a telnet session. The relevant part of the script looks like

telnet mailserver 25 << EOF
EHLO $HOST
MAIL FROM: root@$HOST
(and so on)
EOF

This intermittently fails, with a "connection closed by remote host". A tcpdump of a failing session confirms that the Postfix mail server is closing the connection immediately after sending the 220 welcome message. That is, none of the input redirection has made it over the wire.

So far, I haven't been able to pin down the conditions of the failure, but I can confirm that using nc (netcat) works flawlessly, every time.

A number of questions on this site and Stack Overflow are adamant that nc is the right tool for this job. I am interested in why this is the case.

  • Why is the failure intermittent?
  • Why does the mail server hang up before a single line of input from the redirected is sent over the wire?
  • Why does telnet break but netcat not?

Mikey T.K.

Posted 2017-04-27T21:40:25.970

Reputation: 3 224

Answers

0

This is most likely happening because of delays from the mail host being ignored. Sending an email has a requirement of a connection, then a response. If the MAIL FROM is issued before the server has responded the sending will fail. Indeed some servers rely on slightly delaying this HELO response specifically to stop this pump and close connection behaviour as it is often done by spammers.

There are ways to handle this (not using Telnet being the best one), but otherwise using some kind of chat script. If that is not available to you, manually adding delays will not fix the problem, but it can substantially limit the issue.

As you appear to be using some kind of Linux environment, using nc (netcat) over Telnet is considered best practice. The last part of this link shows how to use netcat and "expect" to better send an email and correctly handle timings.

davidgo

Posted 2017-04-27T21:40:25.970

Reputation: 49 152

Netcat is a replacement for telnet, not something to be used over telnet. If the lack of delay was the problem, netcat would suffer the same fate. – psusi – 2017-04-28T02:35:45.173

In this part of the world "over" in this context "over" implies "in preference to". Using nc to talk on top of telnet is non-nonsensical in this context. – davidgo – 2017-04-28T02:43:38.790

I see, but still why would nc vs telnet make any difference at all? They both connect to the remote host and send what you give them. – psusi – 2017-04-28T13:36:58.920

Precisely the question being asked here... – Mikey T.K. – 2017-04-28T16:27:21.377

@MikeyT.K. Telnet is considered to be an interactive tool while netcat is focussed on scripting. The issue is not telnet but netcat as much as adding time for appropriate responses from the mail server. – davidgo – 2019-10-01T17:39:59.097