I have an interactive terminal program, that accepts stdin (telnet for example).

I want to send it some input before interacting with it, like this:

echo "Hello" | telnet somewhere 123

But that only sends in Hello and kills telnet afterwards. How can I keep telnet alive and route input to it?

  • 1
    Use expect; I don't know the right incantation offhand. – Gilles Mar 10 '12 at 16:36

You can't change what STDIN of telnet is bound to after you start, but you can replace the simple echo with something that will perform more than one action - and let the second action be "copy user input to the target":

{ echo "hello"; cat; } | telnet somewhere 123

You can, naturally, replace cat with anything that will copy from the user and send to telnet.

Keep in mind that this will still be different to just typing into the process. You have attached a pipe to STDIN, rather than a TTY/PTY, so telnet will, for example, be unable to hide a password you type in.

  • 1
    It complains with "cat: -: Resource temporarily unavailable" – Rogach Mar 10 '12 at 16:17
  • Many, but not all, versions of telnet doesn't very much like taking input from a pipe; you many have some trouble getting it to play nicely with human input. You may find using a tool like nc (with telnet negotiation turned on, of course) or a different way of copying input work better for you. The basic pattern remains the same. – Daniel Pittman Mar 10 '12 at 16:26
  • actually, this approach worked for me some time ago, and flawlessly. – Rogach Mar 10 '12 at 16:28
  • nc is great, but how can I make it listen to the connection closing? For some reason, when I "cat" into it, it waits even when connection is closed. – Rogach Mar 10 '12 at 16:33
  • It waits until the input is closed - until cat exits. Since cat has no knowledge of the network connection, it just carries on until you close STDIN or equivalent. – Daniel Pittman Mar 10 '12 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.