/vendor/jruby-1.1.6RC1/lib/ruby/1.8/net/telnet.rb

https://bitbucket.org/nicksieger/advent-jruby · Ruby · 742 lines · 385 code · 38 blank · 319 comment · 73 complexity · 62d3c0dbe0e4f327fa4c980f83fb6715 MD5 · raw file

  1. # = net/telnet.rb - Simple Telnet Client Library
  2. #
  3. # Author:: Wakou Aoyama <wakou@ruby-lang.org>
  4. # Documentation:: William Webber and Wakou Aoyama
  5. #
  6. # This file holds the class Net::Telnet, which provides client-side
  7. # telnet functionality.
  8. #
  9. # For documentation, see Net::Telnet.
  10. #
  11. require "socket"
  12. require "delegate"
  13. require "timeout"
  14. require "English"
  15. module Net
  16. #
  17. # == Net::Telnet
  18. #
  19. # Provides telnet client functionality.
  20. #
  21. # This class also has, through delegation, all the methods of a
  22. # socket object (by default, a +TCPSocket+, but can be set by the
  23. # +Proxy+ option to <tt>new()</tt>). This provides methods such as
  24. # <tt>close()</tt> to end the session and <tt>sysread()</tt> to read
  25. # data directly from the host, instead of via the <tt>waitfor()</tt>
  26. # mechanism. Note that if you do use <tt>sysread()</tt> directly
  27. # when in telnet mode, you should probably pass the output through
  28. # <tt>preprocess()</tt> to extract telnet command sequences.
  29. #
  30. # == Overview
  31. #
  32. # The telnet protocol allows a client to login remotely to a user
  33. # account on a server and execute commands via a shell. The equivalent
  34. # is done by creating a Net::Telnet class with the +Host+ option
  35. # set to your host, calling #login() with your user and password,
  36. # issuing one or more #cmd() calls, and then calling #close()
  37. # to end the session. The #waitfor(), #print(), #puts(), and
  38. # #write() methods, which #cmd() is implemented on top of, are
  39. # only needed if you are doing something more complicated.
  40. #
  41. # A Net::Telnet object can also be used to connect to non-telnet
  42. # services, such as SMTP or HTTP. In this case, you normally
  43. # want to provide the +Port+ option to specify the port to
  44. # connect to, and set the +Telnetmode+ option to false to prevent
  45. # the client from attempting to interpret telnet command sequences.
  46. # Generally, #login() will not work with other protocols, and you
  47. # have to handle authentication yourself.
  48. #
  49. # For some protocols, it will be possible to specify the +Prompt+
  50. # option once when you create the Telnet object and use #cmd() calls;
  51. # for others, you will have to specify the response sequence to
  52. # look for as the Match option to every #cmd() call, or call
  53. # #puts() and #waitfor() directly; for yet others, you will have
  54. # to use #sysread() instead of #waitfor() and parse server
  55. # responses yourself.
  56. #
  57. # It is worth noting that when you create a new Net::Telnet object,
  58. # you can supply a proxy IO channel via the Proxy option. This
  59. # can be used to attach the Telnet object to other Telnet objects,
  60. # to already open sockets, or to any read-write IO object. This
  61. # can be useful, for instance, for setting up a test fixture for
  62. # unit testing.
  63. #
  64. # == Examples
  65. #
  66. # === Log in and send a command, echoing all output to stdout
  67. #
  68. # localhost = Net::Telnet::new("Host" => "localhost",
  69. # "Timeout" => 10,
  70. # "Prompt" => /[$%#>] \z/n)
  71. # localhost.login("username", "password") { |c| print c }
  72. # localhost.cmd("command") { |c| print c }
  73. # localhost.close
  74. #
  75. #
  76. # === Check a POP server to see if you have mail
  77. #
  78. # pop = Net::Telnet::new("Host" => "your_destination_host_here",
  79. # "Port" => 110,
  80. # "Telnetmode" => false,
  81. # "Prompt" => /^\+OK/n)
  82. # pop.cmd("user " + "your_username_here") { |c| print c }
  83. # pop.cmd("pass " + "your_password_here") { |c| print c }
  84. # pop.cmd("list") { |c| print c }
  85. #
  86. # == References
  87. #
  88. # There are a large number of RFCs relevant to the Telnet protocol.
  89. # RFCs 854-861 define the base protocol. For a complete listing
  90. # of relevant RFCs, see
  91. # http://www.omnifarious.org/~hopper/technical/telnet-rfc.html
  92. #
  93. class Telnet < SimpleDelegator
  94. # :stopdoc:
  95. IAC = 255.chr # "\377" # "\xff" # interpret as command
  96. DONT = 254.chr # "\376" # "\xfe" # you are not to use option
  97. DO = 253.chr # "\375" # "\xfd" # please, you use option
  98. WONT = 252.chr # "\374" # "\xfc" # I won't use option
  99. WILL = 251.chr # "\373" # "\xfb" # I will use option
  100. SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation
  101. GA = 249.chr # "\371" # "\xf9" # you may reverse the line
  102. EL = 248.chr # "\370" # "\xf8" # erase the current line
  103. EC = 247.chr # "\367" # "\xf7" # erase the current character
  104. AYT = 246.chr # "\366" # "\xf6" # are you there
  105. AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish
  106. IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently
  107. BREAK = 243.chr # "\363" # "\xf3" # break
  108. DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning
  109. NOP = 241.chr # "\361" # "\xf1" # nop
  110. SE = 240.chr # "\360" # "\xf0" # end sub negotiation
  111. EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode)
  112. ABORT = 238.chr # "\356" # "\xee" # Abort process
  113. SUSP = 237.chr # "\355" # "\xed" # Suspend process
  114. EOF = 236.chr # "\354" # "\xec" # End of file
  115. SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls
  116. OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission
  117. OPT_ECHO = 1.chr # "\001" # "\x01" # Echo
  118. OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection
  119. OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead
  120. OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation
  121. OPT_STATUS = 5.chr # "\005" # "\x05" # Status
  122. OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark
  123. OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo
  124. OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width
  125. OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size
  126. OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition
  127. OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops
  128. OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition
  129. OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition
  130. OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops
  131. OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition
  132. OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition
  133. OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII
  134. OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout
  135. OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro
  136. OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal
  137. OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP
  138. OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output
  139. OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location
  140. OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type
  141. OPT_EOR = 25.chr # "\031" # "\x19" # End of Record
  142. OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification
  143. OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking
  144. OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number
  145. OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime
  146. OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD
  147. OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size
  148. OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed
  149. OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control
  150. OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode
  151. OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location
  152. OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option
  153. OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option
  154. OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option
  155. OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option
  156. OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List
  157. NULL = "\000"
  158. CR = "\015"
  159. LF = "\012"
  160. EOL = CR + LF
  161. REVISION = '$Id: telnet.rb 2062 2006-06-10 19:14:15Z headius $'
  162. # :startdoc:
  163. #
  164. # Creates a new Net::Telnet object.
  165. #
  166. # Attempts to connect to the host (unless the Proxy option is
  167. # provided: see below). If a block is provided, it is yielded
  168. # status messages on the attempt to connect to the server, of
  169. # the form:
  170. #
  171. # Trying localhost...
  172. # Connected to localhost.
  173. #
  174. # +options+ is a hash of options. The following example lists
  175. # all options and their default values.
  176. #
  177. # host = Net::Telnet::new(
  178. # "Host" => "localhost", # default: "localhost"
  179. # "Port" => 23, # default: 23
  180. # "Binmode" => false, # default: false
  181. # "Output_log" => "output_log", # default: nil (no output)
  182. # "Dump_log" => "dump_log", # default: nil (no output)
  183. # "Prompt" => /[$%#>] \z/n, # default: /[$%#>] \z/n
  184. # "Telnetmode" => true, # default: true
  185. # "Timeout" => 10, # default: 10
  186. # # if ignore timeout then set "Timeout" to false.
  187. # "Waittime" => 0, # default: 0
  188. # "Proxy" => proxy # default: nil
  189. # # proxy is Net::Telnet or IO object
  190. # )
  191. #
  192. # The options have the following meanings:
  193. #
  194. # Host:: the hostname or IP address of the host to connect to, as a String.
  195. # Defaults to "localhost".
  196. #
  197. # Port:: the port to connect to. Defaults to 23.
  198. #
  199. # Binmode:: if false (the default), newline substitution is performed.
  200. # Outgoing LF is
  201. # converted to CRLF, and incoming CRLF is converted to LF. If
  202. # true, this substitution is not performed. This value can
  203. # also be set with the #binmode() method. The
  204. # outgoing conversion only applies to the #puts() and #print()
  205. # methods, not the #write() method. The precise nature of
  206. # the newline conversion is also affected by the telnet options
  207. # SGA and BIN.
  208. #
  209. # Output_log:: the name of the file to write connection status messages
  210. # and all received traffic to. In the case of a proper
  211. # Telnet session, this will include the client input as
  212. # echoed by the host; otherwise, it only includes server
  213. # responses. Output is appended verbatim to this file.
  214. # By default, no output log is kept.
  215. #
  216. # Dump_log:: as for Output_log, except that output is written in hexdump
  217. # format (16 bytes per line as hex pairs, followed by their
  218. # printable equivalent), with connection status messages
  219. # preceded by '#', sent traffic preceded by '>', and
  220. # received traffic preceded by '<'. By default, not dump log
  221. # is kept.
  222. #
  223. # Prompt:: a regular expression matching the host's command-line prompt
  224. # sequence. This is needed by the Telnet class to determine
  225. # when the output from a command has finished and the host is
  226. # ready to receive a new command. By default, this regular
  227. # expression is /[$%#>] \z/n.
  228. #
  229. # Telnetmode:: a boolean value, true by default. In telnet mode,
  230. # traffic received from the host is parsed for special
  231. # command sequences, and these sequences are escaped
  232. # in outgoing traffic sent using #puts() or #print()
  233. # (but not #write()). If you are using the Net::Telnet
  234. # object to connect to a non-telnet service (such as
  235. # SMTP or POP), this should be set to "false" to prevent
  236. # undesired data corruption. This value can also be set
  237. # by the #telnetmode() method.
  238. #
  239. # Timeout:: the number of seconds to wait before timing out both the
  240. # initial attempt to connect to host (in this constructor),
  241. # and all attempts to read data from the host (in #waitfor(),
  242. # #cmd(), and #login()). Exceeding this timeout causes a
  243. # TimeoutError to be raised. The default value is 10 seconds.
  244. # You can disable the timeout by setting this value to false.
  245. # In this case, the connect attempt will eventually timeout
  246. # on the underlying connect(2) socket call with an
  247. # Errno::ETIMEDOUT error (but generally only after a few
  248. # minutes), but other attempts to read data from the host
  249. # will hand indefinitely if no data is forthcoming.
  250. #
  251. # Waittime:: the amount of time to wait after seeing what looks like a
  252. # prompt (that is, received data that matches the Prompt
  253. # option regular expression) to see if more data arrives.
  254. # If more data does arrive in this time, Net::Telnet assumes
  255. # that what it saw was not really a prompt. This is to try to
  256. # avoid false matches, but it can also lead to missing real
  257. # prompts (if, for instance, a background process writes to
  258. # the terminal soon after the prompt is displayed). By
  259. # default, set to 0, meaning not to wait for more data.
  260. #
  261. # Proxy:: a proxy object to used instead of opening a direct connection
  262. # to the host. Must be either another Net::Telnet object or
  263. # an IO object. If it is another Net::Telnet object, this
  264. # instance will use that one's socket for communication. If an
  265. # IO object, it is used directly for communication. Any other
  266. # kind of object will cause an error to be raised.
  267. #
  268. def initialize(options) # :yield: mesg
  269. @options = options
  270. @options["Host"] = "localhost" unless @options.has_key?("Host")
  271. @options["Port"] = 23 unless @options.has_key?("Port")
  272. @options["Prompt"] = /[$%#>] \z/n unless @options.has_key?("Prompt")
  273. @options["Timeout"] = 10 unless @options.has_key?("Timeout")
  274. @options["Waittime"] = 0 unless @options.has_key?("Waittime")
  275. unless @options.has_key?("Binmode")
  276. @options["Binmode"] = false
  277. else
  278. unless (true == @options["Binmode"] or false == @options["Binmode"])
  279. raise ArgumentError, "Binmode option must be true or false"
  280. end
  281. end
  282. unless @options.has_key?("Telnetmode")
  283. @options["Telnetmode"] = true
  284. else
  285. unless (true == @options["Telnetmode"] or false == @options["Telnetmode"])
  286. raise ArgumentError, "Telnetmode option must be true or false"
  287. end
  288. end
  289. @telnet_option = { "SGA" => false, "BINARY" => false }
  290. if @options.has_key?("Output_log")
  291. @log = File.open(@options["Output_log"], 'a+')
  292. @log.sync = true
  293. @log.binmode
  294. end
  295. if @options.has_key?("Dump_log")
  296. @dumplog = File.open(@options["Dump_log"], 'a+')
  297. @dumplog.sync = true
  298. @dumplog.binmode
  299. def @dumplog.log_dump(dir, x) # :nodoc:
  300. len = x.length
  301. addr = 0
  302. offset = 0
  303. while 0 < len
  304. if len < 16
  305. line = x[offset, len]
  306. else
  307. line = x[offset, 16]
  308. end
  309. hexvals = line.unpack('H*')[0]
  310. hexvals += ' ' * (32 - hexvals.length)
  311. hexvals = format("%s %s %s %s " * 4, *hexvals.unpack('a2' * 16))
  312. line = line.gsub(/[\000-\037\177-\377]/n, '.')
  313. printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line
  314. addr += 16
  315. offset += 16
  316. len -= 16
  317. end
  318. print "\n"
  319. end
  320. end
  321. if @options.has_key?("Proxy")
  322. if @options["Proxy"].kind_of?(Net::Telnet)
  323. @sock = @options["Proxy"].sock
  324. elsif @options["Proxy"].kind_of?(IO)
  325. @sock = @options["Proxy"]
  326. else
  327. raise "Error: Proxy must be an instance of Net::Telnet or IO."
  328. end
  329. else
  330. message = "Trying " + @options["Host"] + "...\n"
  331. yield(message) if block_given?
  332. @log.write(message) if @options.has_key?("Output_log")
  333. @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
  334. begin
  335. if @options["Timeout"] == false
  336. @sock = TCPSocket.open(@options["Host"], @options["Port"])
  337. else
  338. timeout(@options["Timeout"]) do
  339. @sock = TCPSocket.open(@options["Host"], @options["Port"])
  340. end
  341. end
  342. rescue TimeoutError
  343. raise TimeoutError, "timed out while opening a connection to the host"
  344. rescue
  345. @log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log")
  346. @dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log")
  347. raise
  348. end
  349. @sock.sync = true
  350. @sock.binmode
  351. message = "Connected to " + @options["Host"] + ".\n"
  352. yield(message) if block_given?
  353. @log.write(message) if @options.has_key?("Output_log")
  354. @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
  355. end
  356. super(@sock)
  357. end # initialize
  358. # The socket the Telnet object is using. Note that this object becomes
  359. # a delegate of the Telnet object, so normally you invoke its methods
  360. # directly on the Telnet object.
  361. attr :sock
  362. # Set telnet command interpretation on (+mode+ == true) or off
  363. # (+mode+ == false), or return the current value (+mode+ not
  364. # provided). It should be on for true telnet sessions, off if
  365. # using Net::Telnet to connect to a non-telnet service such
  366. # as SMTP.
  367. def telnetmode(mode = nil)
  368. case mode
  369. when nil
  370. @options["Telnetmode"]
  371. when true, false
  372. @options["Telnetmode"] = mode
  373. else
  374. raise ArgumentError, "argument must be true or false, or missing"
  375. end
  376. end
  377. # Turn telnet command interpretation on (true) or off (false). It
  378. # should be on for true telnet sessions, off if using Net::Telnet
  379. # to connect to a non-telnet service such as SMTP.
  380. def telnetmode=(mode)
  381. if (true == mode or false == mode)
  382. @options["Telnetmode"] = mode
  383. else
  384. raise ArgumentError, "argument must be true or false"
  385. end
  386. end
  387. # Turn newline conversion on (+mode+ == false) or off (+mode+ == true),
  388. # or return the current value (+mode+ is not specified).
  389. def binmode(mode = nil)
  390. case mode
  391. when nil
  392. @options["Binmode"]
  393. when true, false
  394. @options["Binmode"] = mode
  395. else
  396. raise ArgumentError, "argument must be true or false"
  397. end
  398. end
  399. # Turn newline conversion on (false) or off (true).
  400. def binmode=(mode)
  401. if (true == mode or false == mode)
  402. @options["Binmode"] = mode
  403. else
  404. raise ArgumentError, "argument must be true or false"
  405. end
  406. end
  407. # Preprocess received data from the host.
  408. #
  409. # Performs newline conversion and detects telnet command sequences.
  410. # Called automatically by #waitfor(). You should only use this
  411. # method yourself if you have read input directly using sysread()
  412. # or similar, and even then only if in telnet mode.
  413. def preprocess(string)
  414. # combine CR+NULL into CR
  415. string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]
  416. # combine EOL into "\n"
  417. string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"]
  418. string.gsub(/#{IAC}(
  419. [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
  420. [#{DO}#{DONT}#{WILL}#{WONT}]
  421. [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
  422. #{SB}[^#{IAC}]*#{IAC}#{SE}
  423. )/xno) do
  424. if IAC == $1 # handle escaped IAC characters
  425. IAC
  426. elsif AYT == $1 # respond to "IAC AYT" (are you there)
  427. self.write("nobody here but us pigeons" + EOL)
  428. ''
  429. elsif DO[0] == $1[0] # respond to "IAC DO x"
  430. if OPT_BINARY[0] == $1[1]
  431. @telnet_option["BINARY"] = true
  432. self.write(IAC + WILL + OPT_BINARY)
  433. else
  434. self.write(IAC + WONT + $1[1..1])
  435. end
  436. ''
  437. elsif DONT[0] == $1[0] # respond to "IAC DON'T x" with "IAC WON'T x"
  438. self.write(IAC + WONT + $1[1..1])
  439. ''
  440. elsif WILL[0] == $1[0] # respond to "IAC WILL x"
  441. if OPT_BINARY[0] == $1[1]
  442. self.write(IAC + DO + OPT_BINARY)
  443. elsif OPT_ECHO[0] == $1[1]
  444. self.write(IAC + DO + OPT_ECHO)
  445. elsif OPT_SGA[0] == $1[1]
  446. @telnet_option["SGA"] = true
  447. self.write(IAC + DO + OPT_SGA)
  448. else
  449. self.write(IAC + DONT + $1[1..1])
  450. end
  451. ''
  452. elsif WONT[0] == $1[0] # respond to "IAC WON'T x"
  453. if OPT_ECHO[0] == $1[1]
  454. self.write(IAC + DONT + OPT_ECHO)
  455. elsif OPT_SGA[0] == $1[1]
  456. @telnet_option["SGA"] = false
  457. self.write(IAC + DONT + OPT_SGA)
  458. else
  459. self.write(IAC + DONT + $1[1..1])
  460. end
  461. ''
  462. else
  463. ''
  464. end
  465. end
  466. end # preprocess
  467. # Read data from the host until a certain sequence is matched.
  468. #
  469. # If a block is given, the received data will be yielded as it
  470. # is read in (not necessarily all in one go), or nil if EOF
  471. # occurs before any data is received. Whether a block is given
  472. # or not, all data read will be returned in a single string, or again
  473. # nil if EOF occurs before any data is received. Note that
  474. # received data includes the matched sequence we were looking for.
  475. #
  476. # +options+ can be either a regular expression or a hash of options.
  477. # If a regular expression, this specifies the data to wait for.
  478. # If a hash, this can specify the following options:
  479. #
  480. # Match:: a regular expression, specifying the data to wait for.
  481. # Prompt:: as for Match; used only if Match is not specified.
  482. # String:: as for Match, except a string that will be converted
  483. # into a regular expression. Used only if Match and
  484. # Prompt are not specified.
  485. # Timeout:: the number of seconds to wait for data from the host
  486. # before raising a TimeoutError. If set to false,
  487. # no timeout will occur. If not specified, the
  488. # Timeout option value specified when this instance
  489. # was created will be used, or, failing that, the
  490. # default value of 10 seconds.
  491. # Waittime:: the number of seconds to wait after matching against
  492. # the input data to see if more data arrives. If more
  493. # data arrives within this time, we will judge ourselves
  494. # not to have matched successfully, and will continue
  495. # trying to match. If not specified, the Waittime option
  496. # value specified when this instance was created will be
  497. # used, or, failing that, the default value of 0 seconds,
  498. # which means not to wait for more input.
  499. #
  500. def waitfor(options) # :yield: recvdata
  501. time_out = @options["Timeout"]
  502. waittime = @options["Waittime"]
  503. if options.kind_of?(Hash)
  504. prompt = if options.has_key?("Match")
  505. options["Match"]
  506. elsif options.has_key?("Prompt")
  507. options["Prompt"]
  508. elsif options.has_key?("String")
  509. Regexp.new( Regexp.quote(options["String"]) )
  510. end
  511. time_out = options["Timeout"] if options.has_key?("Timeout")
  512. waittime = options["Waittime"] if options.has_key?("Waittime")
  513. else
  514. prompt = options
  515. end
  516. if time_out == false
  517. time_out = nil
  518. end
  519. line = ''
  520. buf = ''
  521. rest = ''
  522. until(prompt === line and not IO::select([@sock], nil, nil, waittime))
  523. unless IO::select([@sock], nil, nil, time_out)
  524. raise TimeoutError, "timed out while waiting for more data"
  525. end
  526. begin
  527. c = @sock.readpartial(1024 * 1024)
  528. @dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
  529. if @options["Telnetmode"]
  530. c = rest + c
  531. if Integer(c.rindex(/#{IAC}#{SE}/no)) <
  532. Integer(c.rindex(/#{IAC}#{SB}/no))
  533. buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
  534. rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
  535. elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no)
  536. buf = preprocess(c[0 ... pt])
  537. rest = c[pt .. -1]
  538. else
  539. buf = preprocess(c)
  540. rest = ''
  541. end
  542. else
  543. # Not Telnetmode.
  544. #
  545. # We cannot use preprocess() on this data, because that
  546. # method makes some Telnetmode-specific assumptions.
  547. buf = c
  548. buf.gsub!(/#{EOL}/no, "\n") unless @options["Binmode"]
  549. rest = ''
  550. end
  551. @log.print(buf) if @options.has_key?("Output_log")
  552. line += buf
  553. yield buf if block_given?
  554. rescue EOFError # End of file reached
  555. if line == ''
  556. line = nil
  557. yield nil if block_given?
  558. end
  559. break
  560. end
  561. end
  562. line
  563. end
  564. # Write +string+ to the host.
  565. #
  566. # Does not perform any conversions on +string+. Will log +string+ to the
  567. # dumplog, if the Dump_log option is set.
  568. def write(string)
  569. length = string.length
  570. while 0 < length
  571. IO::select(nil, [@sock])
  572. @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
  573. length -= @sock.syswrite(string[-length..-1])
  574. end
  575. end
  576. # Sends a string to the host.
  577. #
  578. # This does _not_ automatically append a newline to the string. Embedded
  579. # newlines may be converted and telnet command sequences escaped
  580. # depending upon the values of telnetmode, binmode, and telnet options
  581. # set by the host.
  582. def print(string)
  583. string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]
  584. if @options["Binmode"]
  585. self.write(string)
  586. else
  587. if @telnet_option["BINARY"] and @telnet_option["SGA"]
  588. # IAC WILL SGA IAC DO BIN send EOL --> CR
  589. self.write(string.gsub(/\n/n, CR))
  590. elsif @telnet_option["SGA"]
  591. # IAC WILL SGA send EOL --> CR+NULL
  592. self.write(string.gsub(/\n/n, CR + NULL))
  593. else
  594. # NONE send EOL --> CR+LF
  595. self.write(string.gsub(/\n/n, EOL))
  596. end
  597. end
  598. end
  599. # Sends a string to the host.
  600. #
  601. # Same as #print(), but appends a newline to the string.
  602. def puts(string)
  603. self.print(string + "\n")
  604. end
  605. # Send a command to the host.
  606. #
  607. # More exactly, sends a string to the host, and reads in all received
  608. # data until is sees the prompt or other matched sequence.
  609. #
  610. # If a block is given, the received data will be yielded to it as
  611. # it is read in. Whether a block is given or not, the received data
  612. # will be return as a string. Note that the received data includes
  613. # the prompt and in most cases the host's echo of our command.
  614. #
  615. # +options+ is either a String, specified the string or command to
  616. # send to the host; or it is a hash of options. If a hash, the
  617. # following options can be specified:
  618. #
  619. # String:: the command or other string to send to the host.
  620. # Match:: a regular expression, the sequence to look for in
  621. # the received data before returning. If not specified,
  622. # the Prompt option value specified when this instance
  623. # was created will be used, or, failing that, the default
  624. # prompt of /[$%#>] \z/n.
  625. # Timeout:: the seconds to wait for data from the host before raising
  626. # a Timeout error. If not specified, the Timeout option
  627. # value specified when this instance was created will be
  628. # used, or, failing that, the default value of 10 seconds.
  629. #
  630. # The command or other string will have the newline sequence appended
  631. # to it.
  632. def cmd(options) # :yield: recvdata
  633. match = @options["Prompt"]
  634. time_out = @options["Timeout"]
  635. if options.kind_of?(Hash)
  636. string = options["String"]
  637. match = options["Match"] if options.has_key?("Match")
  638. time_out = options["Timeout"] if options.has_key?("Timeout")
  639. else
  640. string = options
  641. end
  642. self.puts(string)
  643. if block_given?
  644. waitfor({"Prompt" => match, "Timeout" => time_out}){|c| yield c }
  645. else
  646. waitfor({"Prompt" => match, "Timeout" => time_out})
  647. end
  648. end
  649. # Login to the host with a given username and password.
  650. #
  651. # The username and password can either be provided as two string
  652. # arguments in that order, or as a hash with keys "Name" and
  653. # "Password".
  654. #
  655. # This method looks for the strings "login" and "Password" from the
  656. # host to determine when to send the username and password. If the
  657. # login sequence does not follow this pattern (for instance, you
  658. # are connecting to a service other than telnet), you will need
  659. # to handle login yourself.
  660. #
  661. # The password can be omitted, either by only
  662. # provided one String argument, which will be used as the username,
  663. # or by providing a has that has no "Password" key. In this case,
  664. # the method will not look for the "Password:" prompt; if it is
  665. # sent, it will have to be dealt with by later calls.
  666. #
  667. # The method returns all data received during the login process from
  668. # the host, including the echoed username but not the password (which
  669. # the host should not echo). If a block is passed in, this received
  670. # data is also yielded to the block as it is received.
  671. def login(options, password = nil) # :yield: recvdata
  672. login_prompt = /[Ll]ogin[: ]*\z/n
  673. password_prompt = /Password[: ]*\z/n
  674. if options.kind_of?(Hash)
  675. username = options["Name"]
  676. password = options["Password"]
  677. login_prompt = options["LoginPrompt"] if options["LoginPrompt"]
  678. password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"]
  679. else
  680. username = options
  681. end
  682. if block_given?
  683. line = waitfor(login_prompt){|c| yield c }
  684. if password
  685. line += cmd({"String" => username,
  686. "Match" => password_prompt}){|c| yield c }
  687. line += cmd(password){|c| yield c }
  688. else
  689. line += cmd(username){|c| yield c }
  690. end
  691. else
  692. line = waitfor(login_prompt)
  693. if password
  694. line += cmd({"String" => username,
  695. "Match" => password_prompt})
  696. line += cmd(password)
  697. else
  698. line += cmd(username)
  699. end
  700. end
  701. line
  702. end
  703. end # class Telnet
  704. end # module Net