Capture the display of a Rigol DS1000Z series oscilloscope by LAN using LXI SCPI commands
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

telnetlib_receive_all.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. # This whole file is a copy of the 'telnetlib.py' that came with Python 2.7.12 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 = b''
  170. self.irawq = 0
  171. self.cookedq = b''
  172. self.eof = 0
  173. self.iacseq = b'' # Buffer for IAC sequence.
  174. self.sb = 0 # flag for SB and SE sequence.
  175. self.sbdataq = b''
  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. sock = self.sock
  215. self.sock = 0
  216. self.eof = 1
  217. self.iacseq = b''
  218. self.sb = 0
  219. if sock:
  220. sock.close()
  221. def get_socket(self):
  222. """Return the socket object used internally."""
  223. return self.sock
  224. def fileno(self):
  225. """Return the fileno() of the socket object used internally."""
  226. return self.sock.fileno()
  227. def write(self, buffer):
  228. """Write a string to the socket, doubling any IAC characters.
  229. Can block if the connection is blocked. May raise
  230. socket.error if the connection is closed.
  231. """
  232. if IAC in buffer:
  233. buffer = buffer.replace(IAC, IAC+IAC)
  234. self.msg("send %r", buffer)
  235. self.sock.sendall(bytes(buffer, 'ascii'))
  236. def read_until(self, match, timeout=None):
  237. """Read until a given string is encountered or until timeout.
  238. When no match is found, return whatever is available instead,
  239. possibly the empty string. Raise EOFError if the connection
  240. is closed and no cooked data is available.
  241. """
  242. if self._has_poll:
  243. return self._read_until_with_poll(match, timeout)
  244. else:
  245. return self._read_until_with_select(match, timeout)
  246. def _read_until_with_poll(self, match, timeout):
  247. """Read until a given string is encountered or until timeout.
  248. This method uses select.poll() to implement the timeout.
  249. """
  250. n = len(match)
  251. call_timeout = timeout
  252. if timeout is not None:
  253. from time import time
  254. time_start = time()
  255. self.process_rawq()
  256. i = self.cookedq.find(match)
  257. if i < 0:
  258. poller = select.poll()
  259. poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
  260. poller.register(self, poll_in_or_priority_flags)
  261. while i < 0 and not self.eof:
  262. try:
  263. # Poll takes its timeout in milliseconds.
  264. ready = poller.poll(None if timeout is None
  265. else 1000 * call_timeout)
  266. except select.error as e:
  267. if e.errno == errno.EINTR:
  268. if timeout is not None:
  269. elapsed = time() - time_start
  270. call_timeout = timeout-elapsed
  271. continue
  272. raise
  273. for fd, mode in ready:
  274. if mode & poll_in_or_priority_flags:
  275. i = max(0, len(self.cookedq)-n)
  276. self.fill_rawq()
  277. self.process_rawq()
  278. i = self.cookedq.find(match, i)
  279. if timeout is not None:
  280. elapsed = time() - time_start
  281. if elapsed >= timeout:
  282. break
  283. call_timeout = timeout-elapsed
  284. poller.unregister(self)
  285. if i >= 0:
  286. i = i + n
  287. buf = self.cookedq[:i]
  288. self.cookedq = self.cookedq[i:]
  289. return buf
  290. return self.read_very_lazy()
  291. def _read_until_with_select(self, match, timeout=None):
  292. """Read until a given string is encountered or until timeout.
  293. The timeout is implemented using select.select().
  294. """
  295. n = len(match)
  296. self.process_rawq()
  297. i = self.cookedq.find(match)
  298. if i >= 0:
  299. i = i+n
  300. buf = self.cookedq[:i]
  301. self.cookedq = self.cookedq[i:]
  302. return buf
  303. s_reply = ([self], [], [])
  304. s_args = s_reply
  305. if timeout is not None:
  306. s_args = s_args + (timeout,)
  307. from time import time
  308. time_start = time()
  309. while not self.eof and select.select(*s_args) == s_reply:
  310. i = max(0, len(self.cookedq)-n)
  311. self.fill_rawq()
  312. self.process_rawq()
  313. i = self.cookedq.find(match, i)
  314. if i >= 0:
  315. i = i+n
  316. buf = self.cookedq[:i]
  317. self.cookedq = self.cookedq[i:]
  318. return buf
  319. if timeout is not None:
  320. elapsed = time() - time_start
  321. if elapsed >= timeout:
  322. break
  323. s_args = s_reply + (timeout-elapsed,)
  324. return self.read_very_lazy()
  325. def read_all(self):
  326. """Read all data until EOF; block until connection closed."""
  327. self.process_rawq()
  328. while not self.eof:
  329. self.fill_rawq()
  330. self.process_rawq()
  331. buf = self.cookedq
  332. self.cookedq = b''
  333. return buf
  334. def read_some(self):
  335. """Read at least one byte of cooked data unless EOF is hit.
  336. Return '' if EOF is hit. Block if no data is immediately
  337. available.
  338. """
  339. self.process_rawq()
  340. while not self.cookedq and not self.eof:
  341. self.fill_rawq()
  342. self.process_rawq()
  343. buf = self.cookedq
  344. self.cookedq = b''
  345. return buf
  346. def read_very_eager(self):
  347. """Read everything that's possible without blocking in I/O (eager).
  348. Raise EOFError if connection closed and no cooked data
  349. available. Return '' if no cooked data available otherwise.
  350. Don't block unless in the midst of an IAC sequence.
  351. """
  352. self.process_rawq()
  353. while not self.eof and self.sock_avail():
  354. self.fill_rawq()
  355. self.process_rawq()
  356. return self.read_very_lazy()
  357. def read_eager(self):
  358. """Read readily available data.
  359. Raise EOFError if connection closed and no cooked data
  360. available. Return '' if no cooked data available otherwise.
  361. Don't block unless in the midst of an IAC sequence.
  362. """
  363. self.process_rawq()
  364. while not self.cookedq and not self.eof and self.sock_avail():
  365. self.fill_rawq()
  366. self.process_rawq()
  367. return self.read_very_lazy()
  368. def read_lazy(self):
  369. """Process and return data that's already in the queues (lazy).
  370. Raise EOFError if connection closed and no data available.
  371. Return '' if no cooked data available otherwise. Don't block
  372. unless in the midst of an IAC sequence.
  373. """
  374. self.process_rawq()
  375. return self.read_very_lazy()
  376. def read_very_lazy(self):
  377. """Return any data available in the cooked queue (very lazy).
  378. Raise EOFError if connection closed and no data available.
  379. Return '' if no cooked data available otherwise. Don't block.
  380. """
  381. buf = self.cookedq
  382. self.cookedq = b''
  383. if not buf and self.eof and not self.rawq:
  384. raise EOFError ('telnet connection closed')
  385. return buf
  386. def read_sb_data(self):
  387. """Return any data available in the SB ... SE queue.
  388. Return '' if no SB ... SE available. Should only be called
  389. after seeing a SB or SE command. When a new SB command is
  390. found, old unread SB data will be discarded. Don't block.
  391. """
  392. buf = self.sbdataq
  393. self.sbdataq = b''
  394. return buf
  395. def set_option_negotiation_callback(self, callback):
  396. """Provide a callback function called after each receipt of a telnet option."""
  397. self.option_callback = callback
  398. def process_rawq(self):
  399. """Transfer from raw queue to cooked queue.
  400. Set self.eof when connection is closed. Don't block unless in
  401. the midst of an IAC sequence.
  402. """
  403. buf = [b'', b'']
  404. try:
  405. while self.rawq:
  406. c = self.rawq_getchar()
  407. if not self.iacseq:
  408. #if c == theNULL:
  409. # continue
  410. #if c == "\021":
  411. # continue
  412. if c != IAC:
  413. buf[self.sb] = buf[self.sb] + c
  414. continue
  415. else:
  416. self.iacseq += c
  417. elif len(self.iacseq) == 1:
  418. # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
  419. if c in (DO, DONT, WILL, WONT):
  420. self.iacseq += c
  421. continue
  422. self.iacseq = b''
  423. if c == IAC:
  424. buf[self.sb] = buf[self.sb] + c
  425. else:
  426. if c == SB: # SB ... SE start.
  427. self.sb = 1
  428. self.sbdataq = b''
  429. elif c == SE:
  430. self.sb = 0
  431. self.sbdataq = self.sbdataq + buf[1]
  432. buf[1] = b''
  433. if self.option_callback:
  434. # Callback is supposed to look into
  435. # the sbdataq
  436. self.option_callback(self.sock, c, NOOPT)
  437. else:
  438. # We can't offer automatic processing of
  439. # suboptions. Alas, we should not get any
  440. # unless we did a WILL/DO before.
  441. self.msg('IAC %d not recognized' % ord(c))
  442. elif len(self.iacseq) == 2:
  443. cmd = self.iacseq[1]
  444. self.iacseq = b''
  445. opt = c
  446. if cmd in (DO, DONT):
  447. self.msg('IAC %s %d',
  448. cmd == DO and 'DO' or 'DONT', ord(opt))
  449. if self.option_callback:
  450. self.option_callback(self.sock, cmd, opt)
  451. else:
  452. self.sock.sendall(bytes(IAC + WONT + opt, 'ascii'))
  453. elif cmd in (WILL, WONT):
  454. self.msg('IAC %s %d',
  455. cmd == WILL and 'WILL' or 'WONT', ord(opt))
  456. if self.option_callback:
  457. self.option_callback(self.sock, cmd, opt)
  458. else:
  459. self.sock.sendall(bytes(IAC + DONT + opt, 'ascii'))
  460. except EOFError: # raised by self.rawq_getchar()
  461. self.iacseq = b'' # Reset on EOF
  462. self.sb = 0
  463. pass
  464. self.cookedq = self.cookedq + buf[0]
  465. self.sbdataq = self.sbdataq + buf[1]
  466. def rawq_getchar(self):
  467. """Get next char from raw queue.
  468. Block if no data is immediately available. Raise EOFError
  469. when connection is closed.
  470. """
  471. if not self.rawq:
  472. self.fill_rawq()
  473. if self.eof:
  474. raise EOFError
  475. c = self.rawq[self.irawq:self.irawq+1]
  476. self.irawq = self.irawq + 1
  477. if self.irawq >= len(self.rawq):
  478. self.rawq = b''
  479. self.irawq = 0
  480. return c
  481. def fill_rawq(self):
  482. """Fill raw queue from exactly one recv() system call.
  483. Block if no data is immediately available. Set self.eof when
  484. connection is closed.
  485. """
  486. if self.irawq >= len(self.rawq):
  487. self.rawq = b''
  488. self.irawq = 0
  489. # The buffer size should be fairly small so as to avoid quadratic
  490. # behavior in process_rawq() above
  491. buf = self.sock.recv(50)
  492. self.msg("recv %r", buf)
  493. self.eof = (not buf)
  494. self.rawq = self.rawq + buf
  495. def sock_avail(self):
  496. """Test whether data is available on the socket."""
  497. return select.select([self], [], [], 0) == ([self], [], [])
  498. def interact(self):
  499. """Interaction function, emulates a very dumb telnet client."""
  500. if sys.platform == "win32":
  501. self.mt_interact()
  502. return
  503. while 1:
  504. rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
  505. if self in rfd:
  506. try:
  507. text = self.read_eager()
  508. except EOFError:
  509. print ('*** Connection closed by remote host ***')
  510. break
  511. if text:
  512. sys.stdout.write(text)
  513. sys.stdout.flush()
  514. if sys.stdin in rfd:
  515. line = sys.stdin.readline()
  516. if not line:
  517. break
  518. self.write(line)
  519. def mt_interact(self):
  520. """Multithreaded version of interact()."""
  521. import thread
  522. thread.start_new_thread(self.listener, ())
  523. while 1:
  524. line = sys.stdin.readline()
  525. if not line:
  526. break
  527. self.write(line)
  528. def listener(self):
  529. """Helper for mt_interact() -- this executes in the other thread."""
  530. while 1:
  531. try:
  532. data = self.read_eager()
  533. except EOFError:
  534. print ('*** Connection closed by remote host ***')
  535. return
  536. if data:
  537. sys.stdout.write(data)
  538. else:
  539. sys.stdout.flush()
  540. def expect(self, list, timeout=None):
  541. """Read until one from a list of a regular expressions matches.
  542. The first argument is a list of regular expressions, either
  543. compiled (re.RegexObject instances) or uncompiled (strings).
  544. The optional second argument is a timeout, in seconds; default
  545. is no timeout.
  546. Return a tuple of three items: the index in the list of the
  547. first regular expression that matches; the match object
  548. returned; and the text read up till and including the match.
  549. If EOF is read and no text was read, raise EOFError.
  550. Otherwise, when nothing matches, return (-1, None, text) where
  551. text is the text received so far (may be the empty string if a
  552. timeout happened).
  553. If a regular expression ends with a greedy match (e.g. '.*')
  554. or if more than one expression can match the same input, the
  555. results are undeterministic, and may depend on the I/O timing.
  556. """
  557. if self._has_poll:
  558. return self._expect_with_poll(list, timeout)
  559. else:
  560. return self._expect_with_select(list, timeout)
  561. def _expect_with_poll(self, expect_list, timeout=None):
  562. """Read until one from a list of a regular expressions matches.
  563. This method uses select.poll() to implement the timeout.
  564. """
  565. re = None
  566. expect_list = expect_list[:]
  567. indices = range(len(expect_list))
  568. for i in indices:
  569. if not hasattr(expect_list[i], "search"):
  570. if not re: import re
  571. expect_list[i] = re.compile(expect_list[i])
  572. call_timeout = timeout
  573. if timeout is not None:
  574. from time import time
  575. time_start = time()
  576. self.process_rawq()
  577. m = None
  578. for i in indices:
  579. m = expect_list[i].search(self.cookedq)
  580. if m:
  581. e = m.end()
  582. text = self.cookedq[:e]
  583. self.cookedq = self.cookedq[e:]
  584. break
  585. if not m:
  586. poller = select.poll()
  587. poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
  588. poller.register(self, poll_in_or_priority_flags)
  589. while not m and not self.eof:
  590. try:
  591. ready = poller.poll(None if timeout is None
  592. else 1000 * call_timeout)
  593. except select.error as e:
  594. if e.errno == errno.EINTR:
  595. if timeout is not None:
  596. elapsed = time() - time_start
  597. call_timeout = timeout-elapsed
  598. continue
  599. raise
  600. for fd, mode in ready:
  601. if mode & poll_in_or_priority_flags:
  602. self.fill_rawq()
  603. self.process_rawq()
  604. for i in indices:
  605. m = expect_list[i].search(self.cookedq)
  606. if m:
  607. e = m.end()
  608. text = self.cookedq[:e]
  609. self.cookedq = self.cookedq[e:]
  610. break
  611. if timeout is not None:
  612. elapsed = time() - time_start
  613. if elapsed >= timeout:
  614. break
  615. call_timeout = timeout-elapsed
  616. poller.unregister(self)
  617. if m:
  618. return (i, m, text)
  619. text = self.read_very_lazy()
  620. if not text and self.eof:
  621. raise EOFError
  622. return (-1, None, text)
  623. def _expect_with_select(self, list, timeout=None):
  624. """Read until one from a list of a regular expressions matches.
  625. The timeout is implemented using select.select().
  626. """
  627. re = None
  628. list = list[:]
  629. indices = range(len(list))
  630. for i in indices:
  631. if not hasattr(list[i], "search"):
  632. if not re: import re
  633. list[i] = re.compile(list[i])
  634. if timeout is not None:
  635. from time import time
  636. time_start = time()
  637. while 1:
  638. self.process_rawq()
  639. for i in indices:
  640. m = list[i].search(self.cookedq)
  641. if m:
  642. e = m.end()
  643. text = self.cookedq[:e]
  644. self.cookedq = self.cookedq[e:]
  645. return (i, m, text)
  646. if self.eof:
  647. break
  648. if timeout is not None:
  649. elapsed = time() - time_start
  650. if elapsed >= timeout:
  651. break
  652. s_args = ([self.fileno()], [], [], timeout-elapsed)
  653. r, w, x = select.select(*s_args)
  654. if not r:
  655. break
  656. self.fill_rawq()
  657. text = self.read_very_lazy()
  658. if not text and self.eof:
  659. raise EOFError
  660. return (-1, None, text)
  661. def test():
  662. """Test program for telnetlib.
  663. Usage: python telnetlib.py [-d] ... [host [port]]
  664. Default host is localhost; default port is 23.
  665. """
  666. debuglevel = 0
  667. while sys.argv[1:] and sys.argv[1] == '-d':
  668. debuglevel = debuglevel+1
  669. del sys.argv[1]
  670. host = 'localhost'
  671. if sys.argv[1:]:
  672. host = sys.argv[1]
  673. port = 0
  674. if sys.argv[2:]:
  675. portstr = sys.argv[2]
  676. try:
  677. port = int(portstr)
  678. except ValueError:
  679. port = socket.getservbyname(portstr, 'tcp')
  680. tn = Telnet()
  681. tn.set_debuglevel(debuglevel)
  682. tn.open(host, port, timeout=0.5)
  683. tn.interact()
  684. tn.close()
  685. if __name__ == '__main__':
  686. test()