Auto exit Telnet command back to prompt without human intervention ^] quit close exit code 1

前端 未结 5 874
灰色年华
灰色年华 2020-12-31 20:12

I\'m running telnet command on a host for a given port (which is open), it returns 0 (success).

For trying telnet manually, I type the following comman

相关标签:
5条回答
  • 2020-12-31 20:34

    Here is the clean way to do it

    echo -n | telnet `hostname` 2878
    

    For more info on this behavior see this link

    0 讨论(0)
  • 2020-12-31 20:35

    Without using Expect, I guess using the HERE document (<

    [vagrant@myvagrant /tmp] $ telnet_result=$(telnet `hostname` 2878 <<GIGA
    echo ^]
    echo close
    GIGA
    ); echo $telnet_result | grep "Escape character is '^]'"; echo $?
    Connection closed by foreign host.
     Escape character is '^]'.
    0
    [vagrant@myvagrant /tmp] $ 
    

    and for a bad/invalid/non-open port, the same gives 1 (as expected).

    [vagrant@myvagrant /tmp] $ telnet_result=$(telnet `hostname` 287811111 <<GIGA
    echo ^]
    echo close
    GIGA
    ); echo $telnet_result | grep "Escape character is '^]'"; echo $?
    telnet: connect to address 127.0.0.1: Connection refused
    1
    [vagrant@myvagrant /tmp] $ 
    
    0 讨论(0)
  • 2020-12-31 20:42

    A slight improvement to the answer provided by Matthew above which allows you to use it inside shell scripts:

    $ echo -e '\x1dclose\x0d' | telnet google.com 80
    Connected to google.com.
    Escape character is '^]'.
    
    telnet> close
    Connection closed.
    $ echo $?
    0
    
    0 讨论(0)
  • 2020-12-31 20:42
    ╭─ ~
    ╰» echo "^]close^M" | telnet localhost 22; echo $?
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    
    telnet> close
    Connection closed.
    0
    

    To enter the ^] and ^M characters, press ctrl+v ctrt+] and ctrl+v ctrl+m respectively.

    0 讨论(0)
  • 2020-12-31 20:42

    You may need other linux package like expect to achieve what you want.

    0 讨论(0)
提交回复
热议问题