Telnet in script Connection closed by foreign host

Hello,
I'm trying to learn and automate some tasks via a script, but my first ever script failed with "connection closed by foreign host" error. I checked the other discussions but it didn't help. Could you please help?

#!/bin/bash
( sleep 2
 echo open x.x.x.x 23
sleep 2
echo user
sleep 2
echo pass
sleep 2
)  |  telnet 

The following options work without script;

  1. # telnet x.x.x.x
  2. # telnet
    > open x.x.x.x

The script also works for other in-band connection IPs, which directly request user and password without viewing any system info.

We connect this node over auxiliary port via a modem. On putty x.x.x.x 23 connects to our device and x.x.x.x 22 to our server. I got some wireshark captures; the TELNET session continues negotiation, and suddenly interrupts.

I think telnet requires .telnetrc for the initial handshake.
There might be man pages, try

man telnetrc
man telnet

For scripting ssh is better than telnet. An example:

ssh x.x.x.x << "_EOT"
echo "I am on `uname -n`"
_EOT

At first it prompts for a password.
Create a ssh key with ssh-keygen on the remote side, and copy the public key in ~/.ssh/ to the calling side, then it won't prompt for a password.
The full login might complain about a not-working tty. For script-only access it is preferrable to invoke a shell command on the remote side:

ssh x.x.x.x /bin/bash -s <<"_EOT"
...
1 Like