telnetlib.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. sock = None # for __del__()
  163. def __init__(self, host=None, port=0,
  164. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  165. """Constructor.
  166. When called without arguments, create an unconnected instance.
  167. With a hostname argument, it connects the instance; port number
  168. and timeout are optional.
  169. """
  170. self.debuglevel = DEBUGLEVEL
  171. self.host = host
  172. self.port = port
  173. self.timeout = timeout
  174. self.sock = None
  175. self.rawq = b''
  176. self.irawq = 0
  177. self.cookedq = b''
  178. self.eof = 0
  179. self.iacseq = b'' # Buffer for IAC sequence.
  180. self.sb = 0 # flag for SB and SE sequence.
  181. self.sbdataq = b''
  182. self.option_callback = None
  183. if host is not None:
  184. self.open(host, port, timeout)
  185. def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  186. """Connect to a host.
  187. The optional second argument is the port number, which
  188. defaults to the standard telnet port (23).
  189. Don't try to reopen an already connected instance.
  190. """
  191. self.eof = 0
  192. if not port:
  193. port = TELNET_PORT
  194. self.host = host
  195. self.port = port
  196. self.timeout = timeout
  197. sys.audit("telnetlib.Telnet.open", self, host, port)
  198. self.sock = socket.create_connection((host, port), timeout)
  199. def __del__(self):
  200. """Destructor -- close the connection."""
  201. self.close()
  202. def msg(self, msg, *args):
  203. """Print a debug message, when the debug level is > 0.
  204. If extra arguments are present, they are substituted in the
  205. message using the standard string formatting operator.
  206. """
  207. if self.debuglevel > 0:
  208. print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
  209. if args:
  210. print(msg % args)
  211. else:
  212. print(msg)
  213. def set_debuglevel(self, debuglevel):
  214. """Set the debug level.
  215. The higher it is, the more debug output you get (on sys.stdout).
  216. """
  217. self.debuglevel = debuglevel
  218. def close(self):
  219. """Close the connection."""
  220. sock = self.sock
  221. self.sock = None
  222. self.eof = True
  223. self.iacseq = b''
  224. self.sb = 0
  225. if sock:
  226. sock.close()
  227. def get_socket(self):
  228. """Return the socket object used internally."""
  229. return self.sock
  230. def fileno(self):
  231. """Return the fileno() of the socket object used internally."""
  232. return self.sock.fileno()
  233. def write(self, buffer):
  234. """Write a string to the socket, doubling any IAC characters.
  235. Can block if the connection is blocked. May raise
  236. OSError if the connection is closed.
  237. """
  238. if IAC in buffer:
  239. buffer = buffer.replace(IAC, IAC+IAC)
  240. sys.audit("telnetlib.Telnet.write", self, buffer)
  241. self.msg("send %r", buffer)
  242. self.sock.sendall(buffer)
  243. def read_until(self, match, timeout=None):
  244. """Read until a given string is encountered or until timeout.
  245. When no match is found, return whatever is available instead,
  246. possibly the empty string. Raise EOFError if the connection
  247. is closed and no cooked data is available.
  248. """
  249. n = len(match)
  250. self.process_rawq()
  251. i = self.cookedq.find(match)
  252. if i >= 0:
  253. i = i+n
  254. buf = self.cookedq[:i]
  255. self.cookedq = self.cookedq[i:]
  256. return buf
  257. if timeout is not None:
  258. deadline = _time() + timeout
  259. with _TelnetSelector() as selector:
  260. selector.register(self, selectors.EVENT_READ)
  261. while not self.eof:
  262. if selector.select(timeout):
  263. i = max(0, len(self.cookedq)-n)
  264. self.fill_rawq()
  265. self.process_rawq()
  266. i = self.cookedq.find(match, i)
  267. if i >= 0:
  268. i = i+n
  269. buf = self.cookedq[:i]
  270. self.cookedq = self.cookedq[i:]
  271. return buf
  272. if timeout is not None:
  273. timeout = deadline - _time()
  274. if timeout < 0:
  275. break
  276. return self.read_very_lazy()
  277. def read_all(self):
  278. """Read all data until EOF; block until connection closed."""
  279. self.process_rawq()
  280. while not self.eof:
  281. self.fill_rawq()
  282. self.process_rawq()
  283. buf = self.cookedq
  284. self.cookedq = b''
  285. return buf
  286. def read_some(self):
  287. """Read at least one byte of cooked data unless EOF is hit.
  288. Return b'' if EOF is hit. Block if no data is immediately
  289. available.
  290. """
  291. self.process_rawq()
  292. while not self.cookedq and not self.eof:
  293. self.fill_rawq()
  294. self.process_rawq()
  295. buf = self.cookedq
  296. self.cookedq = b''
  297. return buf
  298. def read_very_eager(self):
  299. """Read everything that's possible without blocking in I/O (eager).
  300. Raise EOFError if connection closed and no cooked data
  301. available. Return b'' if no cooked data available otherwise.
  302. Don't block unless in the midst of an IAC sequence.
  303. """
  304. self.process_rawq()
  305. while not self.eof and self.sock_avail():
  306. self.fill_rawq()
  307. self.process_rawq()
  308. return self.read_very_lazy()
  309. def read_eager(self):
  310. """Read readily available data.
  311. Raise EOFError if connection closed and no cooked data
  312. available. Return b'' if no cooked data available otherwise.
  313. Don't block unless in the midst of an IAC sequence.
  314. """
  315. self.process_rawq()
  316. while not self.cookedq and not self.eof and self.sock_avail():
  317. self.fill_rawq()
  318. self.process_rawq()
  319. return self.read_very_lazy()
  320. def read_lazy(self):
  321. """Process and return data that's already in the queues (lazy).
  322. Raise EOFError if connection closed and no data available.
  323. Return b'' if no cooked data available otherwise. Don't block
  324. unless in the midst of an IAC sequence.
  325. """
  326. self.process_rawq()
  327. return self.read_very_lazy()
  328. def read_very_lazy(self):
  329. """Return any data available in the cooked queue (very lazy).
  330. Raise EOFError if connection closed and no data available.
  331. Return b'' if no cooked data available otherwise. Don't block.
  332. """
  333. buf = self.cookedq
  334. self.cookedq = b''
  335. if not buf and self.eof and not self.rawq:
  336. raise EOFError('telnet connection closed')
  337. return buf
  338. def read_sb_data(self):
  339. """Return any data available in the SB ... SE queue.
  340. Return b'' if no SB ... SE available. Should only be called
  341. after seeing a SB or SE command. When a new SB command is
  342. found, old unread SB data will be discarded. Don't block.
  343. """
  344. buf = self.sbdataq
  345. self.sbdataq = b''
  346. return buf
  347. def set_option_negotiation_callback(self, callback):
  348. """Provide a callback function called after each receipt of a telnet option."""
  349. self.option_callback = callback
  350. def process_rawq(self):
  351. """Transfer from raw queue to cooked queue.
  352. Set self.eof when connection is closed. Don't block unless in
  353. the midst of an IAC sequence.
  354. """
  355. buf = [b'', b'']
  356. try:
  357. while self.rawq:
  358. c = self.rawq_getchar()
  359. if not self.iacseq:
  360. if c == theNULL:
  361. continue
  362. if c == b"\021":
  363. continue
  364. if c != IAC:
  365. buf[self.sb] = buf[self.sb] + c
  366. continue
  367. else:
  368. self.iacseq += c
  369. elif len(self.iacseq) == 1:
  370. # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
  371. if c in (DO, DONT, WILL, WONT):
  372. self.iacseq += c
  373. continue
  374. self.iacseq = b''
  375. if c == IAC:
  376. buf[self.sb] = buf[self.sb] + c
  377. else:
  378. if c == SB: # SB ... SE start.
  379. self.sb = 1
  380. self.sbdataq = b''
  381. elif c == SE:
  382. self.sb = 0
  383. self.sbdataq = self.sbdataq + buf[1]
  384. buf[1] = b''
  385. if self.option_callback:
  386. # Callback is supposed to look into
  387. # the sbdataq
  388. self.option_callback(self.sock, c, NOOPT)
  389. else:
  390. # We can't offer automatic processing of
  391. # suboptions. Alas, we should not get any
  392. # unless we did a WILL/DO before.
  393. self.msg('IAC %d not recognized' % ord(c))
  394. elif len(self.iacseq) == 2:
  395. cmd = self.iacseq[1:2]
  396. self.iacseq = b''
  397. opt = c
  398. if cmd in (DO, DONT):
  399. self.msg('IAC %s %d',
  400. cmd == DO and 'DO' or 'DONT', ord(opt))
  401. if self.option_callback:
  402. self.option_callback(self.sock, cmd, opt)
  403. else:
  404. self.sock.sendall(IAC + WONT + opt)
  405. elif cmd in (WILL, WONT):
  406. self.msg('IAC %s %d',
  407. cmd == WILL and 'WILL' or 'WONT', ord(opt))
  408. if self.option_callback:
  409. self.option_callback(self.sock, cmd, opt)
  410. else:
  411. self.sock.sendall(IAC + DONT + opt)
  412. except EOFError: # raised by self.rawq_getchar()
  413. self.iacseq = b'' # Reset on EOF
  414. self.sb = 0
  415. self.cookedq = self.cookedq + buf[0]
  416. self.sbdataq = self.sbdataq + buf[1]
  417. def rawq_getchar(self):
  418. """Get next char from raw queue.
  419. Block if no data is immediately available. Raise EOFError
  420. when connection is closed.
  421. """
  422. if not self.rawq:
  423. self.fill_rawq()
  424. if self.eof:
  425. raise EOFError
  426. c = self.rawq[self.irawq:self.irawq+1]
  427. self.irawq = self.irawq + 1
  428. if self.irawq >= len(self.rawq):
  429. self.rawq = b''
  430. self.irawq = 0
  431. return c
  432. def fill_rawq(self):
  433. """Fill raw queue from exactly one recv() system call.
  434. Block if no data is immediately available. Set self.eof when
  435. connection is closed.
  436. """
  437. if self.irawq >= len(self.rawq):
  438. self.rawq = b''
  439. self.irawq = 0
  440. # The buffer size should be fairly small so as to avoid quadratic
  441. # behavior in process_rawq() above
  442. buf = self.sock.recv(50)
  443. self.msg("recv %r", buf)
  444. self.eof = (not buf)
  445. self.rawq = self.rawq + buf
  446. def sock_avail(self):
  447. """Test whether data is available on the socket."""
  448. with _TelnetSelector() as selector:
  449. selector.register(self, selectors.EVENT_READ)
  450. return bool(selector.select(0))
  451. def interact(self):
  452. """Interaction function, emulates a very dumb telnet client."""
  453. if sys.platform == "win32":
  454. self.mt_interact()
  455. return
  456. with _TelnetSelector() as selector:
  457. selector.register(self, selectors.EVENT_READ)
  458. selector.register(sys.stdin, selectors.EVENT_READ)
  459. while True:
  460. for key, events in selector.select():
  461. if key.fileobj is self:
  462. try:
  463. text = self.read_eager()
  464. except EOFError:
  465. print('*** Connection closed by remote host ***')
  466. return
  467. if text:
  468. sys.stdout.write(text.decode('ascii'))
  469. sys.stdout.flush()
  470. elif key.fileobj is sys.stdin:
  471. line = sys.stdin.readline().encode('ascii')
  472. if not line:
  473. return
  474. self.write(line)
  475. def mt_interact(self):
  476. """Multithreaded version of interact()."""
  477. import _thread
  478. _thread.start_new_thread(self.listener, ())
  479. while 1:
  480. line = sys.stdin.readline()
  481. if not line:
  482. break
  483. self.write(line.encode('ascii'))
  484. def listener(self):
  485. """Helper for mt_interact() -- this executes in the other thread."""
  486. while 1:
  487. try:
  488. data = self.read_eager()
  489. except EOFError:
  490. print('*** Connection closed by remote host ***')
  491. return
  492. if data:
  493. sys.stdout.write(data.decode('ascii'))
  494. else:
  495. sys.stdout.flush()
  496. def expect(self, list, timeout=None):
  497. """Read until one from a list of a regular expressions matches.
  498. The first argument is a list of regular expressions, either
  499. compiled (re.Pattern instances) or uncompiled (strings).
  500. The optional second argument is a timeout, in seconds; default
  501. is no timeout.
  502. Return a tuple of three items: the index in the list of the
  503. first regular expression that matches; the re.Match object
  504. returned; and the text read up till and including the match.
  505. If EOF is read and no text was read, raise EOFError.
  506. Otherwise, when nothing matches, return (-1, None, text) where
  507. text is the text received so far (may be the empty string if a
  508. timeout happened).
  509. If a regular expression ends with a greedy match (e.g. '.*')
  510. or if more than one expression can match the same input, the
  511. results are undeterministic, and may depend on the I/O timing.
  512. """
  513. re = None
  514. list = list[:]
  515. indices = range(len(list))
  516. for i in indices:
  517. if not hasattr(list[i], "search"):
  518. if not re: import re
  519. list[i] = re.compile(list[i])
  520. if timeout is not None:
  521. deadline = _time() + timeout
  522. with _TelnetSelector() as selector:
  523. selector.register(self, selectors.EVENT_READ)
  524. while not self.eof:
  525. self.process_rawq()
  526. for i in indices:
  527. m = list[i].search(self.cookedq)
  528. if m:
  529. e = m.end()
  530. text = self.cookedq[:e]
  531. self.cookedq = self.cookedq[e:]
  532. return (i, m, text)
  533. if timeout is not None:
  534. ready = selector.select(timeout)
  535. timeout = deadline - _time()
  536. if not ready:
  537. if timeout < 0:
  538. break
  539. else:
  540. continue
  541. self.fill_rawq()
  542. text = self.read_very_lazy()
  543. if not text and self.eof:
  544. raise EOFError
  545. return (-1, None, text)
  546. def __enter__(self):
  547. return self
  548. def __exit__(self, type, value, traceback):
  549. self.close()
  550. def test():
  551. """Test program for telnetlib.
  552. Usage: python telnetlib.py [-d] ... [host [port]]
  553. Default host is localhost; default port is 23.
  554. """
  555. debuglevel = 0
  556. while sys.argv[1:] and sys.argv[1] == '-d':
  557. debuglevel = debuglevel+1
  558. del sys.argv[1]
  559. host = 'localhost'
  560. if sys.argv[1:]:
  561. host = sys.argv[1]
  562. port = 0
  563. if sys.argv[2:]:
  564. portstr = sys.argv[2]
  565. try:
  566. port = int(portstr)
  567. except ValueError:
  568. port = socket.getservbyname(portstr, 'tcp')
  569. with Telnet() as tn:
  570. tn.set_debuglevel(debuglevel)
  571. tn.open(host, port, timeout=0.5)
  572. tn.interact()
  573. if __name__ == '__main__':
  574. test()