I would like to initiate a telnet session, send a command, and store the output in a variable using bash. To do this manually, I do:

telnet ip port

However, I'm not sure how to script this. I could easily echo something if I was just retrieving the output of something directly with command1, but I'm not sure how to bring the telnet connection into the equation.

I've tried the following command:

command1 | telnet ip port

This seems to start the telnet session, but then it tells me that the command was not found


1 Answer 1


I think that should be:

cat file_with_command_in | telenet ip port

that way you send all input including newlines etc. (Which I suppose you could do from the command line, but a file is easier).

  • Regarding file_with_command_in, do you mean I need to create a file with that one command, then invoke it from my main script file? If so, is there a way to do it all in one script? My overall goal is to run one script that is bound to a hotkey, save part of the output with command1, then store it as a variable for the rest of my script. Perhaps I should have mentioned that in my question.
    – hiigaran
    Oct 22, 2018 at 0:23
  • What you were doing was sending the output of command1 to telenet. In order to send 'command1' literally you would need echo command1 | telnet ..... Using cat filename is usually easier, but if the requirment is very simple then echo is the same. Oct 22, 2018 at 10:26
  • The response I get is "Trying IP. Connected to IP. Escape character is '^]'. Connection closed by foreign host."
    – hiigaran
    Oct 23, 2018 at 23:22

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.