Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

telnetlib.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. Bugs:
  22. - may hang when connection is slow in the middle of an IAC sequence
  23. To do:
  24. - option negotiation
  25. - timeout should be intrinsic to the connection object instead of an
  26. option on one of the read calls only
  27. """
  28. # Imported modules
  29. import sys
  30. import socket
  31. import select
  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 = chr(255) # "Interpret As Command"
  39. DONT = chr(254)
  40. DO = chr(253)
  41. WONT = chr(252)
  42. WILL = chr(251)
  43. theNULL = chr(0)
  44. class Telnet:
  45. """Telnet interface class.
  46. An instance of this class represents a connection to a telnet
  47. server. The instance is initially not connected; the open()
  48. method must be used to establish a connection. Alternatively, the
  49. host name and optional port number can be passed to the
  50. constructor, too.
  51. Don't try to reopen an already connected instance.
  52. This class has many read_*() methods. Note that some of them
  53. raise EOFError when the end of the connection is read, because
  54. they can return an empty string for other reasons. See the
  55. individual doc strings.
  56. read_until(expected, [timeout])
  57. Read until the expected string has been seen, or a timeout is
  58. hit (default is no timeout); may block.
  59. read_all()
  60. Read all data until EOF; may block.
  61. read_some()
  62. Read at least one byte or EOF; may block.
  63. read_very_eager()
  64. Read all data available already queued or on the socket,
  65. without blocking.
  66. read_eager()
  67. Read either data already queued or some data available on the
  68. socket, without blocking.
  69. read_lazy()
  70. Read all data in the raw queue (processing it first), without
  71. doing any socket I/O.
  72. read_very_lazy()
  73. Reads all data in the cooked queue, without doing any socket
  74. I/O.
  75. """
  76. def __init__(self, host=None, port=0):
  77. """Constructor.
  78. When called without arguments, create an unconnected instance.
  79. With a hostname argument, it connects the instance; a port
  80. number is optional.
  81. """
  82. self.debuglevel = DEBUGLEVEL
  83. self.host = host
  84. self.port = port
  85. self.sock = None
  86. self.rawq = ''
  87. self.irawq = 0
  88. self.cookedq = ''
  89. self.eof = 0
  90. if host:
  91. self.open(host, port)
  92. def open(self, host, port=0):
  93. """Connect to a host.
  94. The optional second argument is the port number, which
  95. defaults to the standard telnet port (23).
  96. Don't try to reopen an already connected instance.
  97. """
  98. self.eof = 0
  99. if not port:
  100. port = TELNET_PORT
  101. self.host = host
  102. self.port = port
  103. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  104. self.sock.connect((self.host, self.port))
  105. def __del__(self):
  106. """Destructor -- close the connection."""
  107. self.close()
  108. def msg(self, msg, *args):
  109. """Print a debug message, when the debug level is > 0.
  110. If extra arguments are present, they are substituted in the
  111. message using the standard string formatting operator.
  112. """
  113. if self.debuglevel > 0:
  114. print 'Telnet(%s,%d):' % (self.host, self.port),
  115. if args:
  116. print msg % args
  117. else:
  118. print msg
  119. def set_debuglevel(self, debuglevel):
  120. """Set the debug level.
  121. The higher it is, the more debug output you get (on sys.stdout).
  122. """
  123. self.debuglevel = debuglevel
  124. def close(self):
  125. """Close the connection."""
  126. if self.sock:
  127. self.sock.close()
  128. self.sock = 0
  129. self.eof = 1
  130. def get_socket(self):
  131. """Return the socket object used internally."""
  132. return self.sock
  133. def fileno(self):
  134. """Return the fileno() of the socket object used internally."""
  135. return self.sock.fileno()
  136. def write(self, buffer):
  137. """Write a string to the socket, doubling any IAC characters.
  138. Can block if the connection is blocked. May raise
  139. socket.error if the connection is closed.
  140. """
  141. if IAC in buffer:
  142. buffer = buffer.replace(IAC, IAC+IAC)
  143. self.msg("send %s", `buffer`)
  144. self.sock.send(buffer)
  145. def read_until(self, match, timeout=None):
  146. """Read until a given string is encountered or until timeout.
  147. When no match is found, return whatever is available instead,
  148. possibly the empty string. Raise EOFError if the connection
  149. is closed and no cooked data is available.
  150. """
  151. n = len(match)
  152. self.process_rawq()
  153. i = self.cookedq.find(match)
  154. if i >= 0:
  155. i = i+n
  156. buf = self.cookedq[:i]
  157. self.cookedq = self.cookedq[i:]
  158. return buf
  159. s_reply = ([self], [], [])
  160. s_args = s_reply
  161. if timeout is not None:
  162. s_args = s_args + (timeout,)
  163. while not self.eof and apply(select.select, s_args) == s_reply:
  164. i = max(0, len(self.cookedq)-n)
  165. self.fill_rawq()
  166. self.process_rawq()
  167. i = self.cookedq.find(match, i)
  168. if i >= 0:
  169. i = i+n
  170. buf = self.cookedq[:i]
  171. self.cookedq = self.cookedq[i:]
  172. return buf
  173. return self.read_very_lazy()
  174. def read_all(self):
  175. """Read all data until EOF; block until connection closed."""
  176. self.process_rawq()
  177. while not self.eof:
  178. self.fill_rawq()
  179. self.process_rawq()
  180. buf = self.cookedq
  181. self.cookedq = ''
  182. return buf
  183. def read_some(self):
  184. """Read at least one byte of cooked data unless EOF is hit.
  185. Return '' if EOF is hit. Block if no data is immediately
  186. available.
  187. """
  188. self.process_rawq()
  189. while not self.cookedq and not self.eof:
  190. self.fill_rawq()
  191. self.process_rawq()
  192. buf = self.cookedq
  193. self.cookedq = ''
  194. return buf
  195. def read_very_eager(self):
  196. """Read everything that's possible without blocking in I/O (eager).
  197. Raise EOFError if connection closed and no cooked data
  198. available. Return '' if no cooked data available otherwise.
  199. Don't block unless in the midst of an IAC sequence.
  200. """
  201. self.process_rawq()
  202. while not self.eof and self.sock_avail():
  203. self.fill_rawq()
  204. self.process_rawq()
  205. return self.read_very_lazy()
  206. def read_eager(self):
  207. """Read readily available data.
  208. Raise EOFError if connection closed and no cooked data
  209. available. Return '' if no cooked data available otherwise.
  210. Don't block unless in the midst of an IAC sequence.
  211. """
  212. self.process_rawq()
  213. while not self.cookedq and not self.eof and self.sock_avail():
  214. self.fill_rawq()
  215. self.process_rawq()
  216. return self.read_very_lazy()
  217. def read_lazy(self):
  218. """Process and return data that's already in the queues (lazy).
  219. Raise EOFError if connection closed and no data available.
  220. Return '' if no cooked data available otherwise. Don't block
  221. unless in the midst of an IAC sequence.
  222. """
  223. self.process_rawq()
  224. return self.read_very_lazy()
  225. def read_very_lazy(self):
  226. """Return any data available in the cooked queue (very lazy).
  227. Raise EOFError if connection closed and no data available.
  228. Return '' if no cooked data available otherwise. Don't block.
  229. """
  230. buf = self.cookedq
  231. self.cookedq = ''
  232. if not buf and self.eof and not self.rawq:
  233. raise EOFError, 'telnet connection closed'
  234. return buf
  235. def process_rawq(self):
  236. """Transfer from raw queue to cooked queue.
  237. Set self.eof when connection is closed. Don't block unless in
  238. the midst of an IAC sequence.
  239. """
  240. buf = ''
  241. try:
  242. while self.rawq:
  243. c = self.rawq_getchar()
  244. if c == theNULL:
  245. continue
  246. if c == "\021":
  247. continue
  248. if c != IAC:
  249. buf = buf + c
  250. continue
  251. c = self.rawq_getchar()
  252. if c == IAC:
  253. buf = buf + c
  254. elif c in (DO, DONT):
  255. opt = self.rawq_getchar()
  256. self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(c))
  257. self.sock.send(IAC + WONT + opt)
  258. elif c in (WILL, WONT):
  259. opt = self.rawq_getchar()
  260. self.msg('IAC %s %d',
  261. c == WILL and 'WILL' or 'WONT', ord(c))
  262. self.sock.send(IAC + DONT + opt)
  263. else:
  264. self.msg('IAC %s not recognized' % `c`)
  265. except EOFError: # raised by self.rawq_getchar()
  266. pass
  267. self.cookedq = self.cookedq + buf
  268. def rawq_getchar(self):
  269. """Get next char from raw queue.
  270. Block if no data is immediately available. Raise EOFError
  271. when connection is closed.
  272. """
  273. if not self.rawq:
  274. self.fill_rawq()
  275. if self.eof:
  276. raise EOFError
  277. c = self.rawq[self.irawq]
  278. self.irawq = self.irawq + 1
  279. if self.irawq >= len(self.rawq):
  280. self.rawq = ''
  281. self.irawq = 0
  282. return c
  283. def fill_rawq(self):
  284. """Fill raw queue from exactly one recv() system call.
  285. Block if no data is immediately available. Set self.eof when
  286. connection is closed.
  287. """
  288. if self.irawq >= len(self.rawq):
  289. self.rawq = ''
  290. self.irawq = 0
  291. # The buffer size should be fairly small so as to avoid quadratic
  292. # behavior in process_rawq() above
  293. buf = self.sock.recv(50)
  294. self.msg("recv %s", `buf`)
  295. self.eof = (not buf)
  296. self.rawq = self.rawq + buf
  297. def sock_avail(self):
  298. """Test whether data is available on the socket."""
  299. return select.select([self], [], [], 0) == ([self], [], [])
  300. def interact(self):
  301. """Interaction function, emulates a very dumb telnet client."""
  302. if sys.platform == "win32":
  303. self.mt_interact()
  304. return
  305. while 1:
  306. rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
  307. if self in rfd:
  308. try:
  309. text = self.read_eager()
  310. except EOFError:
  311. print '*** Connection closed by remote host ***'
  312. break
  313. if text:
  314. sys.stdout.write(text)
  315. sys.stdout.flush()
  316. if sys.stdin in rfd:
  317. line = sys.stdin.readline()
  318. if not line:
  319. break
  320. self.write(line)
  321. def mt_interact(self):
  322. """Multithreaded version of interact()."""
  323. import thread
  324. thread.start_new_thread(self.listener, ())
  325. while 1:
  326. line = sys.stdin.readline()
  327. if not line:
  328. break
  329. self.write(line)
  330. def listener(self):
  331. """Helper for mt_interact() -- this executes in the other thread."""
  332. while 1:
  333. try:
  334. data = self.read_eager()
  335. except EOFError:
  336. print '*** Connection closed by remote host ***'
  337. return
  338. if data:
  339. sys.stdout.write(data)
  340. else:
  341. sys.stdout.flush()
  342. def expect(self, list, timeout=None):
  343. """Read until one from a list of a regular expressions matches.
  344. The first argument is a list of regular expressions, either
  345. compiled (re.RegexObject instances) or uncompiled (strings).
  346. The optional second argument is a timeout, in seconds; default
  347. is no timeout.
  348. Return a tuple of three items: the index in the list of the
  349. first regular expression that matches; the match object
  350. returned; and the text read up till and including the match.
  351. If EOF is read and no text was read, raise EOFError.
  352. Otherwise, when nothing matches, return (-1, None, text) where
  353. text is the text received so far (may be the empty string if a
  354. timeout happened).
  355. If a regular expression ends with a greedy match (e.g. '.*')
  356. or if more than one expression can match the same input, the
  357. results are undeterministic, and may depend on the I/O timing.
  358. """
  359. re = None
  360. list = list[:]
  361. indices = range(len(list))
  362. for i in indices:
  363. if not hasattr(list[i], "search"):
  364. if not re: import re
  365. list[i] = re.compile(list[i])
  366. while 1:
  367. self.process_rawq()
  368. for i in indices:
  369. m = list[i].search(self.cookedq)
  370. if m:
  371. e = m.end()
  372. text = self.cookedq[:e]
  373. self.cookedq = self.cookedq[e:]
  374. return (i, m, text)
  375. if self.eof:
  376. break
  377. if timeout is not None:
  378. r, w, x = select.select([self.fileno()], [], [], timeout)
  379. if not r:
  380. break
  381. self.fill_rawq()
  382. text = self.read_very_lazy()
  383. if not text and self.eof:
  384. raise EOFError
  385. return (-1, None, text)
  386. def test():
  387. """Test program for telnetlib.
  388. Usage: python telnetlib.py [-d] ... [host [port]]
  389. Default host is localhost; default port is 23.
  390. """
  391. debuglevel = 0
  392. while sys.argv[1:] and sys.argv[1] == '-d':
  393. debuglevel = debuglevel+1
  394. del sys.argv[1]
  395. host = 'localhost'
  396. if sys.argv[1:]:
  397. host = sys.argv[1]
  398. port = 0
  399. if sys.argv[2:]:
  400. portstr = sys.argv[2]
  401. try:
  402. port = int(portstr)
  403. except ValueError:
  404. port = socket.getservbyname(portstr, 'tcp')
  405. tn = Telnet()
  406. tn.set_debuglevel(debuglevel)
  407. tn.open(host, port)
  408. tn.interact()
  409. tn.close()
  410. if __name__ == '__main__':
  411. test()