telnetlib.py 23 KB

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