telnetlib.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. """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. """Constructor.
  156. When called without arguments, create an unconnected instance.
  157. With a hostname argument, it connects the instance; a port
  158. number is optional.
  159. """
  160. self.debuglevel = DEBUGLEVEL
  161. self.host = host
  162. self.port = port
  163. self.sock = None
  164. self.rawq = ''
  165. self.irawq = 0
  166. self.cookedq = ''
  167. self.eof = 0
  168. self.iacseq = '' # Buffer for IAC sequence.
  169. self.sb = 0 # flag for SB and SE sequence.
  170. self.sbdataq = ''
  171. self.option_callback = None
  172. if host is not None:
  173. self.open(host, port)
  174. def open(self, host, port=0):
  175. """Connect to a host.
  176. The optional second argument is the port number, which
  177. defaults to the standard telnet port (23).
  178. Don't try to reopen an already connected instance.
  179. """
  180. self.eof = 0
  181. if not port:
  182. port = TELNET_PORT
  183. self.host = host
  184. self.port = port
  185. msg = "getaddrinfo returns an empty list"
  186. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  187. af, socktype, proto, canonname, sa = res
  188. try:
  189. self.sock = socket.socket(af, socktype, proto)
  190. self.sock.connect(sa)
  191. except socket.error, msg:
  192. if self.sock:
  193. self.sock.close()
  194. self.sock = None
  195. continue
  196. break
  197. if not self.sock:
  198. raise socket.error, msg
  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,%d):' % (self.host, self.port),
  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. if self.sock:
  221. self.sock.close()
  222. self.sock = 0
  223. self.eof = 1
  224. self.iacseq = ''
  225. self.sb = 0
  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. socket.error if the connection is closed.
  236. """
  237. if IAC in buffer:
  238. buffer = buffer.replace(IAC, IAC+IAC)
  239. self.msg("send %r", buffer)
  240. self.sock.sendall(buffer)
  241. def read_until(self, match, timeout=None):
  242. """Read until a given string is encountered or until timeout.
  243. When no match is found, return whatever is available instead,
  244. possibly the empty string. Raise EOFError if the connection
  245. is closed and no cooked data is available.
  246. """
  247. n = len(match)
  248. self.process_rawq()
  249. i = self.cookedq.find(match)
  250. if i >= 0:
  251. i = i+n
  252. buf = self.cookedq[:i]
  253. self.cookedq = self.cookedq[i:]
  254. return buf
  255. s_reply = ([self], [], [])
  256. s_args = s_reply
  257. if timeout is not None:
  258. s_args = s_args + (timeout,)
  259. from time import time
  260. time_start = time()
  261. while not self.eof and select.select(*s_args) == s_reply:
  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. elapsed = time() - time_start
  273. if elapsed >= timeout:
  274. break
  275. s_args = s_reply + (timeout-elapsed,)
  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 = ''
  285. return buf
  286. def read_some(self):
  287. """Read at least one byte of cooked data unless EOF is hit.
  288. Return '' 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 = ''
  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 '' 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 '' 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 '' 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 '' if no cooked data available otherwise. Don't block.
  332. """
  333. buf = self.cookedq
  334. self.cookedq = ''
  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 '' 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 = ''
  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 = ['', '']
  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 == "\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 = ''
  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 = ''
  381. elif c == SE:
  382. self.sb = 0
  383. self.sbdataq = self.sbdataq + buf[1]
  384. buf[1] = ''
  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]
  396. self.iacseq = ''
  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 = '' # Reset on EOF
  414. self.sb = 0
  415. pass
  416. self.cookedq = self.cookedq + buf[0]
  417. self.sbdataq = self.sbdataq + buf[1]
  418. def rawq_getchar(self):
  419. """Get next char from raw queue.
  420. Block if no data is immediately available. Raise EOFError
  421. when connection is closed.
  422. """
  423. if not self.rawq:
  424. self.fill_rawq()
  425. if self.eof:
  426. raise EOFError
  427. c = self.rawq[self.irawq]
  428. self.irawq = self.irawq + 1
  429. if self.irawq >= len(self.rawq):
  430. self.rawq = ''
  431. self.irawq = 0
  432. return c
  433. def fill_rawq(self):
  434. """Fill raw queue from exactly one recv() system call.
  435. Block if no data is immediately available. Set self.eof when
  436. connection is closed.
  437. """
  438. if self.irawq >= len(self.rawq):
  439. self.rawq = ''
  440. self.irawq = 0
  441. # The buffer size should be fairly small so as to avoid quadratic
  442. # behavior in process_rawq() above
  443. buf = self.sock.recv(50)
  444. self.msg("recv %r", buf)
  445. self.eof = (not buf)
  446. self.rawq = self.rawq + buf
  447. def sock_avail(self):
  448. """Test whether data is available on the socket."""
  449. return select.select([self], [], [], 0) == ([self], [], [])
  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. while 1:
  456. rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
  457. if self in rfd:
  458. try:
  459. text = self.read_eager()
  460. except EOFError:
  461. print '*** Connection closed by remote host ***'
  462. break
  463. if text:
  464. sys.stdout.write(text)
  465. sys.stdout.flush()
  466. if sys.stdin in rfd:
  467. line = sys.stdin.readline()
  468. if not line:
  469. break
  470. self.write(line)
  471. def mt_interact(self):
  472. """Multithreaded version of interact()."""
  473. import thread
  474. thread.start_new_thread(self.listener, ())
  475. while 1:
  476. line = sys.stdin.readline()
  477. if not line:
  478. break
  479. self.write(line)
  480. def listener(self):
  481. """Helper for mt_interact() -- this executes in the other thread."""
  482. while 1:
  483. try:
  484. data = self.read_eager()
  485. except EOFError:
  486. print '*** Connection closed by remote host ***'
  487. return
  488. if data:
  489. sys.stdout.write(data)
  490. else:
  491. sys.stdout.flush()
  492. def expect(self, list, timeout=None):
  493. """Read until one from a list of a regular expressions matches.
  494. The first argument is a list of regular expressions, either
  495. compiled (re.RegexObject instances) or uncompiled (strings).
  496. The optional second argument is a timeout, in seconds; default
  497. is no timeout.
  498. Return a tuple of three items: the index in the list of the
  499. first regular expression that matches; the match object
  500. returned; and the text read up till and including the match.
  501. If EOF is read and no text was read, raise EOFError.
  502. Otherwise, when nothing matches, return (-1, None, text) where
  503. text is the text received so far (may be the empty string if a
  504. timeout happened).
  505. If a regular expression ends with a greedy match (e.g. '.*')
  506. or if more than one expression can match the same input, the
  507. results are undeterministic, and may depend on the I/O timing.
  508. """
  509. re = None
  510. list = list[:]
  511. indices = range(len(list))
  512. for i in indices:
  513. if not hasattr(list[i], "search"):
  514. if not re: import re
  515. list[i] = re.compile(list[i])
  516. if timeout is not None:
  517. from time import time
  518. time_start = time()
  519. while 1:
  520. self.process_rawq()
  521. for i in indices:
  522. m = list[i].search(self.cookedq)
  523. if m:
  524. e = m.end()
  525. text = self.cookedq[:e]
  526. self.cookedq = self.cookedq[e:]
  527. return (i, m, text)
  528. if self.eof:
  529. break
  530. if timeout is not None:
  531. elapsed = time() - time_start
  532. if elapsed >= timeout:
  533. break
  534. s_args = ([self.fileno()], [], [], timeout-elapsed)
  535. r, w, x = select.select(*s_args)
  536. if not r:
  537. break
  538. self.fill_rawq()
  539. text = self.read_very_lazy()
  540. if not text and self.eof:
  541. raise EOFError
  542. return (-1, None, text)
  543. def test():
  544. """Test program for telnetlib.
  545. Usage: python telnetlib.py [-d] ... [host [port]]
  546. Default host is localhost; default port is 23.
  547. """
  548. debuglevel = 0
  549. while sys.argv[1:] and sys.argv[1] == '-d':
  550. debuglevel = debuglevel+1
  551. del sys.argv[1]
  552. host = 'localhost'
  553. if sys.argv[1:]:
  554. host = sys.argv[1]
  555. port = 0
  556. if sys.argv[2:]:
  557. portstr = sys.argv[2]
  558. try:
  559. port = int(portstr)
  560. except ValueError:
  561. port = socket.getservbyname(portstr, 'tcp')
  562. tn = Telnet()
  563. tn.set_debuglevel(debuglevel)
  564. tn.open(host, port)
  565. tn.interact()
  566. tn.close()
  567. if __name__ == '__main__':
  568. test()