PageRenderTime 27ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/telnetlib.py

http://github.com/IronLanguages/main
Python | 791 lines | 744 code | 15 blank | 32 comment | 7 complexity | 99226a33721e4bcb3e79619d35ffd52d MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. r"""TELNET client class.
  2. Based on RFC 854: TELNET Protocol Specification, by J. Postel and
  3. J. Reynolds
  4. Example:
  5. >>> from telnetlib import Telnet
  6. >>> tn = Telnet('www.python.org', 79) # connect to finger port
  7. >>> tn.write('guido\r\n')
  8. >>> print tn.read_all()
  9. Login Name TTY Idle When Where
  10. guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
  11. >>>
  12. Note that read_all() won't read until eof -- it just reads some data
  13. -- but it guarantees to read at least one byte unless EOF is hit.
  14. It is possible to pass a Telnet object to select.select() in order to
  15. wait until more data is available. Note that in this case,
  16. read_eager() may return '' even if there was data on the socket,
  17. because the protocol negotiation may have eaten the data. This is why
  18. EOFError is needed in some cases to distinguish between "no data" and
  19. "connection closed" (since the socket also appears ready for reading
  20. when it is closed).
  21. To do:
  22. - option negotiation
  23. - timeout should be intrinsic to the connection object instead of an
  24. option on one of the read calls only
  25. """
  26. # Imported modules
  27. import errno
  28. import sys
  29. import socket
  30. import select
  31. __all__ = ["Telnet"]
  32. # Tunable parameters
  33. DEBUGLEVEL = 0
  34. # Telnet protocol defaults
  35. TELNET_PORT = 23
  36. # Telnet protocol characters (don't change)
  37. IAC = chr(255) # "Interpret As Command"
  38. DONT = chr(254)
  39. DO = chr(253)
  40. WONT = chr(252)
  41. WILL = chr(251)
  42. theNULL = chr(0)
  43. SE = chr(240) # Subnegotiation End
  44. NOP = chr(241) # No Operation
  45. DM = chr(242) # Data Mark
  46. BRK = chr(243) # Break
  47. IP = chr(244) # Interrupt process
  48. AO = chr(245) # Abort output
  49. AYT = chr(246) # Are You There
  50. EC = chr(247) # Erase Character
  51. EL = chr(248) # Erase Line
  52. GA = chr(249) # Go Ahead
  53. SB = chr(250) # Subnegotiation Begin
  54. # Telnet protocol options code (don't change)
  55. # These ones all come from arpa/telnet.h
  56. BINARY = chr(0) # 8-bit data path
  57. ECHO = chr(1) # echo
  58. RCP = chr(2) # prepare to reconnect
  59. SGA = chr(3) # suppress go ahead
  60. NAMS = chr(4) # approximate message size
  61. STATUS = chr(5) # give status
  62. TM = chr(6) # timing mark
  63. RCTE = chr(7) # remote controlled transmission and echo
  64. NAOL = chr(8) # negotiate about output line width
  65. NAOP = chr(9) # negotiate about output page size
  66. NAOCRD = chr(10) # negotiate about CR disposition
  67. NAOHTS = chr(11) # negotiate about horizontal tabstops
  68. NAOHTD = chr(12) # negotiate about horizontal tab disposition
  69. NAOFFD = chr(13) # negotiate about formfeed disposition
  70. NAOVTS = chr(14) # negotiate about vertical tab stops
  71. NAOVTD = chr(15) # negotiate about vertical tab disposition
  72. NAOLFD = chr(16) # negotiate about output LF disposition
  73. XASCII = chr(17) # extended ascii character set
  74. LOGOUT = chr(18) # force logout
  75. BM = chr(19) # byte macro
  76. DET = chr(20) # data entry terminal
  77. SUPDUP = chr(21) # supdup protocol
  78. SUPDUPOUTPUT = chr(22) # supdup output
  79. SNDLOC = chr(23) # send location
  80. TTYPE = chr(24) # terminal type
  81. EOR = chr(25) # end or record
  82. TUID = chr(26) # TACACS user identification
  83. OUTMRK = chr(27) # output marking
  84. TTYLOC = chr(28) # terminal location number
  85. VT3270REGIME = chr(29) # 3270 regime
  86. X3PAD = chr(30) # X.3 PAD
  87. NAWS = chr(31) # window size
  88. TSPEED = chr(32) # terminal speed
  89. LFLOW = chr(33) # remote flow control
  90. LINEMODE = chr(34) # Linemode option
  91. XDISPLOC = chr(35) # X Display Location
  92. OLD_ENVIRON = chr(36) # Old - Environment variables
  93. AUTHENTICATION = chr(37) # Authenticate
  94. ENCRYPT = chr(38) # Encryption option
  95. NEW_ENVIRON = chr(39) # New - Environment variables
  96. # the following ones come from
  97. # http://www.iana.org/assignments/telnet-options
  98. # Unfortunately, that document does not assign identifiers
  99. # to all of them, so we are making them up
  100. TN3270E = chr(40) # TN3270E
  101. XAUTH = chr(41) # XAUTH
  102. CHARSET = chr(42) # CHARSET
  103. RSP = chr(43) # Telnet Remote Serial Port
  104. COM_PORT_OPTION = chr(44) # Com Port Control Option
  105. SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
  106. TLS = chr(46) # Telnet Start TLS
  107. KERMIT = chr(47) # KERMIT
  108. SEND_URL = chr(48) # SEND-URL
  109. FORWARD_X = chr(49) # FORWARD_X
  110. PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
  111. SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
  112. PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
  113. EXOPL = chr(255) # Extended-Options-List
  114. NOOPT = chr(0)
  115. class Telnet:
  116. """Telnet interface class.
  117. An instance of this class represents a connection to a telnet
  118. server. The instance is initially not connected; the open()
  119. method must be used to establish a connection. Alternatively, the
  120. host name and optional port number can be passed to the
  121. constructor, too.
  122. Don't try to reopen an already connected instance.
  123. This class has many read_*() methods. Note that some of them
  124. raise EOFError when the end of the connection is read, because
  125. they can return an empty string for other reasons. See the
  126. individual doc strings.
  127. read_until(expected, [timeout])
  128. Read until the expected string has been seen, or a timeout is
  129. hit (default is no timeout); may block.
  130. read_all()
  131. Read all data until EOF; may block.
  132. read_some()
  133. Read at least one byte or EOF; may block.
  134. read_very_eager()
  135. Read all data available already queued or on the socket,
  136. without blocking.
  137. read_eager()
  138. Read either data already queued or some data available on the
  139. socket, without blocking.
  140. read_lazy()
  141. Read all data in the raw queue (processing it first), without
  142. doing any socket I/O.
  143. read_very_lazy()
  144. Reads all data in the cooked queue, without doing any socket
  145. I/O.
  146. read_sb_data()
  147. Reads available data between SB ... SE sequence. Don't block.
  148. set_option_negotiation_callback(callback)
  149. Each time a telnet option is read on the input flow, this callback
  150. (if set) is called with the following parameters :
  151. callback(telnet socket, command, option)
  152. option will be chr(0) when there is no option.
  153. No other action is done afterwards by telnetlib.
  154. """
  155. def __init__(self, host=None, port=0,
  156. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  157. """Constructor.
  158. When called without arguments, create an unconnected instance.
  159. With a hostname argument, it connects the instance; port number
  160. and timeout are optional.
  161. """
  162. self.debuglevel = DEBUGLEVEL
  163. self.host = host
  164. self.port = port
  165. self.timeout = timeout
  166. self.sock = None
  167. self.rawq = ''
  168. self.irawq = 0
  169. self.cookedq = ''
  170. self.eof = 0
  171. self.iacseq = '' # Buffer for IAC sequence.
  172. self.sb = 0 # flag for SB and SE sequence.
  173. self.sbdataq = ''
  174. self.option_callback = None
  175. self._has_poll = hasattr(select, 'poll')
  176. if host is not None:
  177. self.open(host, port, timeout)
  178. def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  179. """Connect to a host.
  180. The optional second argument is the port number, which
  181. defaults to the standard telnet port (23).
  182. Don't try to reopen an already connected instance.
  183. """
  184. self.eof = 0
  185. if not port:
  186. port = TELNET_PORT
  187. self.host = host
  188. self.port = port
  189. self.timeout = timeout
  190. self.sock = socket.create_connection((host, port), timeout)
  191. def __del__(self):
  192. """Destructor -- close the connection."""
  193. self.close()
  194. def msg(self, msg, *args):
  195. """Print a debug message, when the debug level is > 0.
  196. If extra arguments are present, they are substituted in the
  197. message using the standard string formatting operator.
  198. """
  199. if self.debuglevel > 0:
  200. print 'Telnet(%s,%s):' % (self.host, self.port),
  201. if args:
  202. print msg % args
  203. else:
  204. print msg
  205. def set_debuglevel(self, debuglevel):
  206. """Set the debug level.
  207. The higher it is, the more debug output you get (on sys.stdout).
  208. """
  209. self.debuglevel = debuglevel
  210. def close(self):
  211. """Close the connection."""
  212. sock = self.sock
  213. self.sock = 0
  214. self.eof = 1
  215. self.iacseq = ''
  216. self.sb = 0
  217. if sock:
  218. sock.close()
  219. def get_socket(self):
  220. """Return the socket object used internally."""
  221. return self.sock
  222. def fileno(self):
  223. """Return the fileno() of the socket object used internally."""
  224. return self.sock.fileno()
  225. def write(self, buffer):
  226. """Write a string to the socket, doubling any IAC characters.
  227. Can block if the connection is blocked. May raise
  228. socket.error if the connection is closed.
  229. """
  230. if IAC in buffer:
  231. buffer = buffer.replace(IAC, IAC+IAC)
  232. self.msg("send %r", buffer)
  233. self.sock.sendall(buffer)
  234. def read_until(self, match, timeout=None):
  235. """Read until a given string is encountered or until timeout.
  236. When no match is found, return whatever is available instead,
  237. possibly the empty string. Raise EOFError if the connection
  238. is closed and no cooked data is available.
  239. """
  240. if self._has_poll:
  241. return self._read_until_with_poll(match, timeout)
  242. else:
  243. return self._read_until_with_select(match, timeout)
  244. def _read_until_with_poll(self, match, timeout):
  245. """Read until a given string is encountered or until timeout.
  246. This method uses select.poll() to implement the timeout.
  247. """
  248. n = len(match)
  249. call_timeout = timeout
  250. if timeout is not None:
  251. from time import time
  252. time_start = time()
  253. self.process_rawq()
  254. i = self.cookedq.find(match)
  255. if i < 0:
  256. poller = select.poll()
  257. poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
  258. poller.register(self, poll_in_or_priority_flags)
  259. while i < 0 and not self.eof:
  260. try:
  261. # Poll takes its timeout in milliseconds.
  262. ready = poller.poll(None if timeout is None
  263. else 1000 * call_timeout)
  264. except select.error as e:
  265. if e.errno == errno.EINTR:
  266. if timeout is not None:
  267. elapsed = time() - time_start
  268. call_timeout = timeout-elapsed
  269. continue
  270. raise
  271. for fd, mode in ready:
  272. if mode & poll_in_or_priority_flags:
  273. i = max(0, len(self.cookedq)-n)
  274. self.fill_rawq()
  275. self.process_rawq()
  276. i = self.cookedq.find(match, i)
  277. if timeout is not None:
  278. elapsed = time() - time_start
  279. if elapsed >= timeout:
  280. break
  281. call_timeout = timeout-elapsed
  282. poller.unregister(self)
  283. if i >= 0:
  284. i = i + n
  285. buf = self.cookedq[:i]
  286. self.cookedq = self.cookedq[i:]
  287. return buf
  288. return self.read_very_lazy()
  289. def _read_until_with_select(self, match, timeout=None):
  290. """Read until a given string is encountered or until timeout.
  291. The timeout is implemented using select.select().
  292. """
  293. n = len(match)
  294. self.process_rawq()
  295. i = self.cookedq.find(match)
  296. if i >= 0:
  297. i = i+n
  298. buf = self.cookedq[:i]
  299. self.cookedq = self.cookedq[i:]
  300. return buf
  301. s_reply = ([self], [], [])
  302. s_args = s_reply
  303. if timeout is not None:
  304. s_args = s_args + (timeout,)
  305. from time import time
  306. time_start = time()
  307. while not self.eof and select.select(*s_args) == s_reply:
  308. i = max(0, len(self.cookedq)-n)
  309. self.fill_rawq()
  310. self.process_rawq()
  311. i = self.cookedq.find(match, i)
  312. if i >= 0:
  313. i = i+n
  314. buf = self.cookedq[:i]
  315. self.cookedq = self.cookedq[i:]
  316. return buf
  317. if timeout is not None:
  318. elapsed = time() - time_start
  319. if elapsed >= timeout:
  320. break
  321. s_args = s_reply + (timeout-elapsed,)
  322. return self.read_very_lazy()
  323. def read_all(self):
  324. """Read all data until EOF; block until connection closed."""
  325. self.process_rawq()
  326. while not self.eof:
  327. self.fill_rawq()
  328. self.process_rawq()
  329. buf = self.cookedq
  330. self.cookedq = ''
  331. return buf
  332. def read_some(self):
  333. """Read at least one byte of cooked data unless EOF is hit.
  334. Return '' if EOF is hit. Block if no data is immediately
  335. available.
  336. """
  337. self.process_rawq()
  338. while not self.cookedq and not self.eof:
  339. self.fill_rawq()
  340. self.process_rawq()
  341. buf = self.cookedq
  342. self.cookedq = ''
  343. return buf
  344. def read_very_eager(self):
  345. """Read everything that's possible without blocking in I/O (eager).
  346. Raise EOFError if connection closed and no cooked data
  347. available. Return '' if no cooked data available otherwise.
  348. Don't block unless in the midst of an IAC sequence.
  349. """
  350. self.process_rawq()
  351. while not self.eof and self.sock_avail():
  352. self.fill_rawq()
  353. self.process_rawq()
  354. return self.read_very_lazy()
  355. def read_eager(self):
  356. """Read readily available data.
  357. Raise EOFError if connection closed and no cooked data
  358. available. Return '' if no cooked data available otherwise.
  359. Don't block unless in the midst of an IAC sequence.
  360. """
  361. self.process_rawq()
  362. while not self.cookedq and not self.eof and self.sock_avail():
  363. self.fill_rawq()
  364. self.process_rawq()
  365. return self.read_very_lazy()
  366. def read_lazy(self):
  367. """Process and return data that's already in the queues (lazy).
  368. Raise EOFError if connection closed and no data available.
  369. Return '' if no cooked data available otherwise. Don't block
  370. unless in the midst of an IAC sequence.
  371. """
  372. self.process_rawq()
  373. return self.read_very_lazy()
  374. def read_very_lazy(self):
  375. """Return any data available in the cooked queue (very lazy).
  376. Raise EOFError if connection closed and no data available.
  377. Return '' if no cooked data available otherwise. Don't block.
  378. """
  379. buf = self.cookedq
  380. self.cookedq = ''
  381. if not buf and self.eof and not self.rawq:
  382. raise EOFError, 'telnet connection closed'
  383. return buf
  384. def read_sb_data(self):
  385. """Return any data available in the SB ... SE queue.
  386. Return '' if no SB ... SE available. Should only be called
  387. after seeing a SB or SE command. When a new SB command is
  388. found, old unread SB data will be discarded. Don't block.
  389. """
  390. buf = self.sbdataq
  391. self.sbdataq = ''
  392. return buf
  393. def set_option_negotiation_callback(self, callback):
  394. """Provide a callback function called after each receipt of a telnet option."""
  395. self.option_callback = callback
  396. def process_rawq(self):
  397. """Transfer from raw queue to cooked queue.
  398. Set self.eof when connection is closed. Don't block unless in
  399. the midst of an IAC sequence.
  400. """
  401. buf = ['', '']
  402. try:
  403. while self.rawq:
  404. c = self.rawq_getchar()
  405. if not self.iacseq:
  406. if c == theNULL:
  407. continue
  408. if c == "\021":
  409. continue
  410. if c != IAC:
  411. buf[self.sb] = buf[self.sb] + c
  412. continue
  413. else:
  414. self.iacseq += c
  415. elif len(self.iacseq) == 1:
  416. # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
  417. if c in (DO, DONT, WILL, WONT):
  418. self.iacseq += c
  419. continue
  420. self.iacseq = ''
  421. if c == IAC:
  422. buf[self.sb] = buf[self.sb] + c
  423. else:
  424. if c == SB: # SB ... SE start.
  425. self.sb = 1
  426. self.sbdataq = ''
  427. elif c == SE:
  428. self.sb = 0
  429. self.sbdataq = self.sbdataq + buf[1]
  430. buf[1] = ''
  431. if self.option_callback:
  432. # Callback is supposed to look into
  433. # the sbdataq
  434. self.option_callback(self.sock, c, NOOPT)
  435. else:
  436. # We can't offer automatic processing of
  437. # suboptions. Alas, we should not get any
  438. # unless we did a WILL/DO before.
  439. self.msg('IAC %d not recognized' % ord(c))
  440. elif len(self.iacseq) == 2:
  441. cmd = self.iacseq[1]
  442. self.iacseq = ''
  443. opt = c
  444. if cmd in (DO, DONT):
  445. self.msg('IAC %s %d',
  446. cmd == DO and 'DO' or 'DONT', ord(opt))
  447. if self.option_callback:
  448. self.option_callback(self.sock, cmd, opt)
  449. else:
  450. self.sock.sendall(IAC + WONT + opt)
  451. elif cmd in (WILL, WONT):
  452. self.msg('IAC %s %d',
  453. cmd == WILL and 'WILL' or 'WONT', ord(opt))
  454. if self.option_callback:
  455. self.option_callback(self.sock, cmd, opt)
  456. else:
  457. self.sock.sendall(IAC + DONT + opt)
  458. except EOFError: # raised by self.rawq_getchar()
  459. self.iacseq = '' # Reset on EOF
  460. self.sb = 0
  461. pass
  462. self.cookedq = self.cookedq + buf[0]
  463. self.sbdataq = self.sbdataq + buf[1]
  464. def rawq_getchar(self):
  465. """Get next char from raw queue.
  466. Block if no data is immediately available. Raise EOFError
  467. when connection is closed.
  468. """
  469. if not self.rawq:
  470. self.fill_rawq()
  471. if self.eof:
  472. raise EOFError
  473. c = self.rawq[self.irawq]
  474. self.irawq = self.irawq + 1
  475. if self.irawq >= len(self.rawq):
  476. self.rawq = ''
  477. self.irawq = 0
  478. return c
  479. def fill_rawq(self):
  480. """Fill raw queue from exactly one recv() system call.
  481. Block if no data is immediately available. Set self.eof when
  482. connection is closed.
  483. """
  484. if self.irawq >= len(self.rawq):
  485. self.rawq = ''
  486. self.irawq = 0
  487. # The buffer size should be fairly small so as to avoid quadratic
  488. # behavior in process_rawq() above
  489. buf = self.sock.recv(50)
  490. self.msg("recv %r", buf)
  491. self.eof = (not buf)
  492. self.rawq = self.rawq + buf
  493. def sock_avail(self):
  494. """Test whether data is available on the socket."""
  495. return select.select([self], [], [], 0) == ([self], [], [])
  496. def interact(self):
  497. """Interaction function, emulates a very dumb telnet client."""
  498. if sys.platform == "win32":
  499. self.mt_interact()
  500. return
  501. while 1:
  502. rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
  503. if self in rfd:
  504. try:
  505. text = self.read_eager()
  506. except EOFError:
  507. print '*** Connection closed by remote host ***'
  508. break
  509. if text:
  510. sys.stdout.write(text)
  511. sys.stdout.flush()
  512. if sys.stdin in rfd:
  513. line = sys.stdin.readline()
  514. if not line:
  515. break
  516. self.write(line)
  517. def mt_interact(self):
  518. """Multithreaded version of interact()."""
  519. import thread
  520. thread.start_new_thread(self.listener, ())
  521. while 1:
  522. line = sys.stdin.readline()
  523. if not line:
  524. break
  525. self.write(line)
  526. def listener(self):
  527. """Helper for mt_interact() -- this executes in the other thread."""
  528. while 1:
  529. try:
  530. data = self.read_eager()
  531. except EOFError:
  532. print '*** Connection closed by remote host ***'
  533. return
  534. if data:
  535. sys.stdout.write(data)
  536. else:
  537. sys.stdout.flush()
  538. def expect(self, list, timeout=None):
  539. """Read until one from a list of a regular expressions matches.
  540. The first argument is a list of regular expressions, either
  541. compiled (re.RegexObject instances) or uncompiled (strings).
  542. The optional second argument is a timeout, in seconds; default
  543. is no timeout.
  544. Return a tuple of three items: the index in the list of the
  545. first regular expression that matches; the match object
  546. returned; and the text read up till and including the match.
  547. If EOF is read and no text was read, raise EOFError.
  548. Otherwise, when nothing matches, return (-1, None, text) where
  549. text is the text received so far (may be the empty string if a
  550. timeout happened).
  551. If a regular expression ends with a greedy match (e.g. '.*')
  552. or if more than one expression can match the same input, the
  553. results are undeterministic, and may depend on the I/O timing.
  554. """
  555. if self._has_poll:
  556. return self._expect_with_poll(list, timeout)
  557. else:
  558. return self._expect_with_select(list, timeout)
  559. def _expect_with_poll(self, expect_list, timeout=None):
  560. """Read until one from a list of a regular expressions matches.
  561. This method uses select.poll() to implement the timeout.
  562. """
  563. re = None
  564. expect_list = expect_list[:]
  565. indices = range(len(expect_list))
  566. for i in indices:
  567. if not hasattr(expect_list[i], "search"):
  568. if not re: import re
  569. expect_list[i] = re.compile(expect_list[i])
  570. call_timeout = timeout
  571. if timeout is not None:
  572. from time import time
  573. time_start = time()
  574. self.process_rawq()
  575. m = None
  576. for i in indices:
  577. m = expect_list[i].search(self.cookedq)
  578. if m:
  579. e = m.end()
  580. text = self.cookedq[:e]
  581. self.cookedq = self.cookedq[e:]
  582. break
  583. if not m:
  584. poller = select.poll()
  585. poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
  586. poller.register(self, poll_in_or_priority_flags)
  587. while not m and not self.eof:
  588. try:
  589. ready = poller.poll(None if timeout is None
  590. else 1000 * call_timeout)
  591. except select.error as e:
  592. if e.errno == errno.EINTR:
  593. if timeout is not None:
  594. elapsed = time() - time_start
  595. call_timeout = timeout-elapsed
  596. continue
  597. raise
  598. for fd, mode in ready:
  599. if mode & poll_in_or_priority_flags:
  600. self.fill_rawq()
  601. self.process_rawq()
  602. for i in indices:
  603. m = expect_list[i].search(self.cookedq)
  604. if m:
  605. e = m.end()
  606. text = self.cookedq[:e]
  607. self.cookedq = self.cookedq[e:]
  608. break
  609. if timeout is not None:
  610. elapsed = time() - time_start
  611. if elapsed >= timeout:
  612. break
  613. call_timeout = timeout-elapsed
  614. poller.unregister(self)
  615. if m:
  616. return (i, m, text)
  617. text = self.read_very_lazy()
  618. if not text and self.eof:
  619. raise EOFError
  620. return (-1, None, text)
  621. def _expect_with_select(self, list, timeout=None):
  622. """Read until one from a list of a regular expressions matches.
  623. The timeout is implemented using select.select().
  624. """
  625. re = None
  626. list = list[:]
  627. indices = range(len(list))
  628. for i in indices:
  629. if not hasattr(list[i], "search"):
  630. if not re: import re
  631. list[i] = re.compile(list[i])
  632. if timeout is not None:
  633. from time import time
  634. time_start = time()
  635. while 1:
  636. self.process_rawq()
  637. for i in indices:
  638. m = list[i].search(self.cookedq)
  639. if m:
  640. e = m.end()
  641. text = self.cookedq[:e]
  642. self.cookedq = self.cookedq[e:]
  643. return (i, m, text)
  644. if self.eof:
  645. break
  646. if timeout is not None:
  647. elapsed = time() - time_start
  648. if elapsed >= timeout:
  649. break
  650. s_args = ([self.fileno()], [], [], timeout-elapsed)
  651. r, w, x = select.select(*s_args)
  652. if not r:
  653. break
  654. self.fill_rawq()
  655. text = self.read_very_lazy()
  656. if not text and self.eof:
  657. raise EOFError
  658. return (-1, None, text)
  659. def test():
  660. """Test program for telnetlib.
  661. Usage: python telnetlib.py [-d] ... [host [port]]
  662. Default host is localhost; default port is 23.
  663. """
  664. debuglevel = 0
  665. while sys.argv[1:] and sys.argv[1] == '-d':
  666. debuglevel = debuglevel+1
  667. del sys.argv[1]
  668. host = 'localhost'
  669. if sys.argv[1:]:
  670. host = sys.argv[1]
  671. port = 0
  672. if sys.argv[2:]:
  673. portstr = sys.argv[2]
  674. try:
  675. port = int(portstr)
  676. except ValueError:
  677. port = socket.getservbyname(portstr, 'tcp')
  678. tn = Telnet()
  679. tn.set_debuglevel(debuglevel)
  680. tn.open(host, port, timeout=0.5)
  681. tn.interact()
  682. tn.close()
  683. if __name__ == '__main__':
  684. test()