19

hey i can login into telnet with "telnet localhost 4242" now i want to execute a single command "show network".

How can i do this in one line ?

something like that

$ telnet localhost 4242 <- "show network"

woa here the output i want

Nick Russler
  • 4,608
  • 6
  • 51
  • 88

2 Answers2

22

I found expect to do exactly what i want, wait for a certain output and then act upon it:

expect << EOF
spawn telnet localhost 4242
expect -re ".*>"
send "show network\r"
expect -re ".*>"
send "exit\r"
EOF
Nick Russler
  • 4,608
  • 6
  • 51
  • 88
4

If you don't have to log in or anything, you can use a "here document" like this:

telnet localhost 4242 << EOF
show network
EOF
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • 2
    Yes, it absolutely does; for example, if you use port 25, you can send mail this way, or port 80, you can fetch a web page this way -- people do it all the time. As I said, it works if you don't need to log in. Now, if you want to provide more details than "doesn't work", maybe we can help you figure out what to do. – Ernest Friedman-Hill Apr 05 '11 at 12:12
  • 1
    thats more readable: http://pastebin.com/ZdckuFxq when i use what you posted i get: Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Welcome to the OpenBSC Control interface Copyright (C) 2008-2010 Harald Welte, Holger Freyther Contributions by Daniel Willmann, Jan Lübbe,Stefan Schmidt Dieter Spaar, Andreas Eversberg License GPLv2+: GNU GPL [...] permitted by law. Connection closed by foreign host. i used now expect to get what i want expect << EOF spawn telnet localhost 4242 expect -re ".*>" send "show network\r" expect -re ".*>" send "exit\r" EOF – Nick Russler Apr 05 '11 at 12:29
  • @nick, you might want to provide your comment as an answer, and you are free to accept your own answer to your question. – glenn jackman Apr 05 '11 at 14:19
  • 1
    @ErnestFriedman-Hill it really doesn't. For example, on this RHEL server I just tried to run `telnet host port <<< 'stats'` to get the stats of a memcached server and got nothing but disconnected, but when I ran telnet interactively and typed `stats` I got the stats I wanted. Perhaps your implementation of `telnet` is special? – kojiro Sep 27 '12 at 16:20
  • 4
    It's likely that the telnet program closes as soon as it finishes sending its input without waiting and displaying any data coming back. For sending an email, the return data is not important which is why it would work in that case. – Brian White Oct 04 '12 at 15:50
  • or `echo show network | telnet localhost 4242` – Apteryx Feb 11 '22 at 21:46