telnetlib.py 23 KB

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