Method: Net::Telnet#initialize

Defined in:
lib/net/telnet.rb

#initialize(options) ⇒ Telnet

Creates a new Net::Telnet object.

Attempts to connect to the host (unless the Proxy option is provided: see below). If a block is provided, it is yielded status messages on the attempt to connect to the server, of the form:

Trying localhost...
Connected to localhost.

options is a hash of options. The following example lists all options and their default values.

host = Net::Telnet::new(
         "Host"       => "localhost",  # default: "localhost"
         "Port"       => 23,           # default: 23
         "Binmode"    => false,        # default: false
         "Output_log" => "output_log", # default: nil (no output)
         "Dump_log"   => "dump_log",   # default: nil (no output)
         "Prompt"     => /[$%#>] \z/n, # default: /[$%#>] \z/n
         "Telnetmode" => true,         # default: true
         "Timeout"    => 10,           # default: 10
           # if ignore timeout then set "Timeout" to false.
         "Waittime"   => 0,            # default: 0
         "Proxy"      => proxy         # default: nil
                         # proxy is Net::Telnet or IO object
       )

The options have the following meanings:

Host

the hostname or IP address of the host to connect to, as a String. Defaults to “localhost”.

Port

the port to connect to. Defaults to 23.

Binmode

if false (the default), newline substitution is performed. Outgoing LF is converted to CRLF, and incoming CRLF is converted to LF. If true, this substitution is not performed. This value can also be set with the #binmode() method. The outgoing conversion only applies to the #puts() and #print() methods, not the #write() method. The precise nature of the newline conversion is also affected by the telnet options SGA and BIN.

Output_log

the name of the file to write connection status messages and all received traffic to. In the case of a proper Telnet session, this will include the client input as echoed by the host; otherwise, it only includes server responses. Output is appended verbatim to this file. By default, no output log is kept.

Dump_log

as for Output_log, except that output is written in hexdump format (16 bytes per line as hex pairs, followed by their printable equivalent), with connection status messages preceded by ‘#’, sent traffic preceded by ‘>’, and received traffic preceded by ‘<’. By default, not dump log is kept.

Prompt

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.

Telnetmode

a boolean value, true by default. In telnet mode, traffic received from the host is parsed for special command sequences, and these sequences are escaped in outgoing traffic sent using #puts() or #print() (but not #write()). If you are using the Net::Telnet object to connect to a non-telnet service (such as SMTP or POP), this should be set to “false” to prevent undesired data corruption. This value can also be set by the #telnetmode() method.

Timeout

the number of seconds to wait before timing out both the initial attempt to connect to host (in this constructor), which raises a Net::OpenTimeout, and all attempts to read data from the host, which raises a Net::ReadTimeout (in #waitfor(), #cmd(), and #login()). The default value is 10 seconds. You can disable the timeout by setting this value to false. In this case, the connect attempt will eventually timeout on the underlying connect(2) socket call with an Errno::ETIMEDOUT error (but generally only after a few minutes), but other attempts to read data from the host will hang indefinitely if no data is forthcoming.

Waittime

the amount of time to wait after seeing what looks like a prompt (that is, received data that matches the Prompt option regular expression) to see if more data arrives. If more data does arrive in this time, Net::Telnet assumes that what it saw was not really a prompt. This is to try to avoid false matches, but it can also lead to missing real prompts (if, for instance, a background process writes to the terminal soon after the prompt is displayed). By default, set to 0, meaning not to wait for more data.

Proxy

a proxy object to used instead of opening a direct connection to the host. Must be either another Net::Telnet object or an IO object. If it is another Net::Telnet object, this instance will use that one’s socket for communication. If an IO object, it is used directly for communication. Any other kind of object will cause an error to be raised.



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/net/telnet.rb', line 273

def initialize(options) # :yield: mesg
  @options = options
  @options["Host"]       = "localhost"   unless @options.has_key?("Host")
  @options["Port"]       = 23            unless @options.has_key?("Port")
  @options["Prompt"]     = /[$%#>] \z/n  unless @options.has_key?("Prompt")
  @options["Timeout"]    = 10            unless @options.has_key?("Timeout")
  @options["Waittime"]   = 0             unless @options.has_key?("Waittime")
  unless @options.has_key?("Binmode")
    @options["Binmode"]    = false
  else
    unless (true == @options["Binmode"] or false == @options["Binmode"])
      raise ArgumentError, "Binmode option must be true or false"
    end
  end

  unless @options.has_key?("Telnetmode")
    @options["Telnetmode"] = true
  else
    unless (true == @options["Telnetmode"] or false == @options["Telnetmode"])
      raise ArgumentError, "Telnetmode option must be true or false"
    end
  end

  @telnet_option = { "SGA" => false, "BINARY" => false }

  if @options.has_key?("Output_log")
    @log = File.open(@options["Output_log"], 'a+')
    @log.sync = true
    @log.binmode
  end

  if @options.has_key?("Dump_log")
    @dumplog = File.open(@options["Dump_log"], 'a+')
    @dumplog.sync = true
    @dumplog.binmode
    def @dumplog.log_dump(dir, x)  # :nodoc:
      len = x.length
      addr = 0
      offset = 0
      while 0 < len
        if len < 16
          line = x[offset, len]
        else
          line = x[offset, 16]
        end
        hexvals = line.unpack('H*')[0]
        hexvals += ' ' * (32 - hexvals.length)
        hexvals = format("%s %s %s %s  " * 4, *hexvals.unpack('a2' * 16))
        line = line.gsub(/[\000-\037\177-\377]/n, '.')
        printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line
        addr += 16
        offset += 16
        len -= 16
      end
      print "\n"
    end
  end

  if @options.has_key?("Proxy")
    if @options["Proxy"].kind_of?(Net::Telnet)
      @sock = @options["Proxy"].sock
    elsif @options["Proxy"].kind_of?(IO)
      @sock = @options["Proxy"]
    else
      raise "Error: Proxy must be an instance of Net::Telnet or IO."
    end
  else
    message = "Trying " + @options["Host"] + "...\n"
    yield(message) if block_given?
    @log.write(message) if @options.has_key?("Output_log")
    @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")

    begin
      if @options["Timeout"] == false
        @sock = TCPSocket.open(@options["Host"], @options["Port"])
      else
        Timeout.timeout(@options["Timeout"], Net::OpenTimeout) do
          @sock = TCPSocket.open(@options["Host"], @options["Port"])
        end
      end
    rescue Net::OpenTimeout
      raise Net::OpenTimeout, "timed out while opening a connection to the host"
    rescue
      @log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log")
      @dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log")
      raise
    end
    @sock.sync = true
    @sock.binmode

    message = "Connected to " + @options["Host"] + ".\n"
    yield(message) if block_given?
    @log.write(message) if @options.has_key?("Output_log")
    @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
  end

end