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

/lib-python/2.7/telnetlib.py

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