1 """TELNET client class.
3 Based on RFC 854: TELNET Protocol Specification, by J. Postel and
8 >>> from telnetlib import Telnet
9 >>> tn = Telnet('www.python.org', 79) # connect to finger port
10 >>> tn.write('guido\r\n')
11 >>> print tn.read_all()
12 Login Name TTY Idle When Where
13 guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
17 Note that read_all() won't read until eof -- it just reads some data
18 -- but it guarantees to read at least one byte unless EOF is hit.
20 It is possible to pass a Telnet object to select.select() in order to
21 wait until more data is available. Note that in this case,
22 read_eager() may return '' even if there was data on the socket,
23 because the protocol negotiation may have eaten the data. This is why
24 EOFError is needed in some cases to distinguish between "no data" and
25 "connection closed" (since the socket also appears ready for reading
29 - may hang when connection is slow in the middle of an IAC sequence
33 - timeout should be intrinsic to the connection object instead of an
34 option on one of the read calls only
84 SUPDUPOUTPUT = chr(22)
91 VT3270REGIME = chr(29)
99 AUTHENTICATION = chr(37)
101 NEW_ENVIRON = chr(39)
110 COM_PORT_OPTION = chr(44)
111 SUPPRESS_LOCAL_ECHO = chr(45)
116 PRAGMA_LOGON = chr(138)
117 SSPI_LOGON = chr(139)
118 PRAGMA_HEARTBEAT = chr(140)
123 """Telnet interface class.
125 An instance of this class represents a connection to a telnet
126 server. The instance is initially not connected; the open()
127 method must be used to establish a connection. Alternatively, the
128 host name and optional port number can be passed to the
131 Don't try to reopen an already connected instance.
133 This class has many read_*() methods. Note that some of them
134 raise EOFError when the end of the connection is read, because
135 they can return an empty string for other reasons. See the
136 individual doc strings.
138 read_until(expected, [timeout])
139 Read until the expected string has been seen, or a timeout is
140 hit (default is no timeout); may block.
143 Read all data until EOF; may block.
146 Read at least one byte or EOF; may block.
149 Read all data available already queued or on the socket,
153 Read either data already queued or some data available on the
154 socket, without blocking.
157 Read all data in the raw queue (processing it first), without
158 doing any socket I/O.
161 Reads all data in the cooked queue, without doing any socket
164 set_option_negotiation_callback(callback)
165 Each time a telnet option is read on the input flow, this callback
166 (if set) is called with the following parameters :
167 callback(telnet socket, command (DO/DONT/WILL/WONT), option)
168 No other action is done afterwards by telnetlib.
175 When called without arguments, create an unconnected instance.
176 With a hostname argument, it connects the instance; a port
190 self.
open(host, port)
193 """Connect to a host.
195 The optional second argument is the port number, which
196 defaults to the standard telnet port (23).
198 Don't try to reopen an already connected instance.
206 msg =
"getaddrinfo returns an empty list"
207 for res
in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
208 af, socktype, proto, canonname, sa = res
211 self.sock.connect(sa)
212 except socket.error, msg:
219 raise socket.error, msg
222 """Destructor -- close the connection."""
225 def msg(self, msg, *args):
226 """Print a debug message, when the debug level is > 0.
228 If extra arguments are present, they are substituted in the
229 message using the standard string formatting operator.
233 print 'Telnet(%s,%d):' % (self.
host, self.
port),
240 """Set the debug level.
242 The higher it is, the more debug output you get (on sys.stdout).
248 """Close the connection."""
255 """Return the socket object used internally."""
259 """Return the fileno() of the socket object used internally."""
260 return self.sock.fileno()
263 """Write a string to the socket, doubling any IAC characters.
265 Can block if the connection is blocked. May raise
266 socket.error if the connection is closed.
270 buffer = buffer.replace(IAC, IAC+IAC)
271 self.
msg(
"send %s", `buffer`)
272 self.sock.sendall(buffer)
275 """Read until a given string is encountered or until timeout.
277 When no match is found, return whatever is available instead,
278 possibly the empty string. Raise EOFError if the connection
279 is closed and no cooked data is available.
284 i = self.cookedq.find(match)
290 s_reply = ([self], [], [])
292 if timeout
is not None:
293 s_args = s_args + (timeout,)
294 while not self.
eof and apply(select.select, s_args) == s_reply:
298 i = self.cookedq.find(match, i)
307 """Read all data until EOF; block until connection closed."""
317 """Read at least one byte of cooked data unless EOF is hit.
319 Return '' if EOF is hit. Block if no data is immediately
332 """Read everything that's possible without blocking in I/O (eager).
334 Raise EOFError if connection closed and no cooked data
335 available. Return '' if no cooked data available otherwise.
336 Don't block unless in the midst of an IAC sequence.
346 """Read readily available data.
348 Raise EOFError if connection closed and no cooked data
349 available. Return '' if no cooked data available otherwise.
350 Don't block unless in the midst of an IAC sequence.
360 """Process and return data that's already in the queues (lazy).
362 Raise EOFError if connection closed and no data available.
363 Return '' if no cooked data available otherwise. Don't block
364 unless in the midst of an IAC sequence.
371 """Return any data available in the cooked queue (very lazy).
373 Raise EOFError if connection closed and no data available.
374 Return '' if no cooked data available otherwise. Don't block.
379 if not buf
and self.
eof and not self.
rawq:
380 raise EOFError,
'telnet connection closed'
384 """Provide a callback function called after each receipt of a telnet option."""
388 """Transfer from raw queue to cooked queue.
390 Set self.eof when connection is closed. Don't block unless in
391 the midst of an IAC sequence.
408 elif c
in (DO, DONT):
410 self.
msg(
'IAC %s %d', c == DO
and 'DO' or 'DONT', ord(opt))
414 self.sock.sendall(IAC + WONT + opt)
415 elif c
in (WILL, WONT):
417 self.
msg(
'IAC %s %d',
418 c == WILL
and 'WILL' or 'WONT', ord(opt))
422 self.sock.sendall(IAC + DONT + opt)
424 self.
msg(
'IAC %d not recognized' % ord(opt))
430 """Get next char from raw queue.
432 Block if no data is immediately available. Raise EOFError
433 when connection is closed.
448 """Fill raw queue from exactly one recv() system call.
450 Block if no data is immediately available. Set self.eof when
451 connection is closed.
459 buf = self.sock.recv(50)
460 self.
msg(
"recv %s", `buf`)
465 """Test whether data is available on the socket."""
466 return select.select([self], [], [], 0) == ([self], [], [])
469 """Interaction function, emulates a very dumb telnet client."""
470 if sys.platform ==
"win32":
474 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
479 print '*** Connection closed by remote host ***'
482 sys.stdout.write(text)
485 line = sys.stdin.readline()
491 """Multithreaded version of interact()."""
493 thread.start_new_thread(self.
listener, ())
495 line = sys.stdin.readline()
501 """Helper for mt_interact() -- this executes in the other thread."""
506 print '*** Connection closed by remote host ***'
509 sys.stdout.write(data)
514 """Read until one from a list of a regular expressions matches.
516 The first argument is a list of regular expressions, either
517 compiled (re.RegexObject instances) or uncompiled (strings).
518 The optional second argument is a timeout, in seconds; default
521 Return a tuple of three items: the index in the list of the
522 first regular expression that matches; the match object
523 returned; and the text read up till and including the match.
525 If EOF is read and no text was read, raise EOFError.
526 Otherwise, when nothing matches, return (-1, None, text) where
527 text is the text received so far (may be the empty string if a
530 If a regular expression ends with a greedy match (e.g. '.*')
531 or if more than one expression can match the same input, the
532 results are undeterministic, and may depend on the I/O timing.
537 indices = range(len(list))
539 if not hasattr(list[i],
"search"):
541 list[i] = re.compile(list[i])
553 if timeout
is not None:
554 r, w, x = select.select([self.
fileno()], [], [], timeout)
559 if not text
and self.
eof:
561 return (-1,
None, text)
565 """Test program for telnetlib.
567 Usage: python telnetlib.py [-d] ... [host [port]]
569 Default host is localhost; default port is 23.
573 while sys.argv[1:]
and sys.argv[1] ==
'-d':
574 debuglevel = debuglevel+1
581 portstr = sys.argv[2]
585 port = socket.getservbyname(portstr,
'tcp')
587 tn.set_debuglevel(debuglevel)
592 if __name__ ==
'__main__':