Capture the display of a Rigol DS1000Z series oscilloscope by LAN using LXI SCPI commands
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

telnetlib_receive_all.py 27KB

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