Search code examples
rubytelnet

Telnet does not close the connection


Have simple ruby script - gives queue list from memcacheq service.

require 'net/telnet'

host = Net::Telnet::new("Host" => "127.0.0.1", "Port" => 22201, "Telnetmode" => false)
host.cmd("stats queue") { |q| puts q }
host.close

Have next output

STAT email_v2_websiteusers 4770/4770
STAT media_casting 7444/7444
STAT encoder_v1_job 7479/7479
STAT pg_generator 163/163
STAT streaming_session_stats 163756/163756
STAT pg_export 150/150
END

But then script does not close, it waiting a few seconds and returned error:

/usr/lib/ruby/1.9.1/net/telnet.rb:558:in `waitfor': timed out while waiting for more data (Timeout::Error)
    from /usr/lib/ruby/1.9.1/net/telnet.rb:695:in `cmd'
    from memcacheq-metrics.rb:18:in `<main>'

Why the connection is not closed after close command?


Solution

  • It's looking for the "Prompt" regexp to know that the command has finished.

    From the docs:

    Prompt/Match
    a regular expression matching the host’s command-line prompt sequence. This is needed by the Telnet class to determine when the output from a command has finished and the host is ready to receive a new command. By default, this regular expression is /[$%#>] z/n.

    Since stats queue ends with END then something like this should work.

    # Change cmd to wait for "END"
    host.cmd("String" => "stats queue", "Match" => /^END/) { |q| puts q }
    host.close