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
49 # Telnet protocol defaults
52 # Telnet protocol characters (don't change)
53 IAC
= chr(255) # "Interpret As Command"
60 # Telnet protocol options code (don't change)
61 # These ones all come from arpa/telnet.h
62 BINARY
= chr(0) # 8-bit data path
64 RCP
= chr(2) # prepare to reconnect
65 SGA
= chr(3) # suppress go ahead
66 NAMS
= chr(4) # approximate message size
67 STATUS
= chr(5) # give status
68 TM
= chr(6) # timing mark
69 RCTE
= chr(7) # remote controlled transmission and echo
70 NAOL
= chr(8) # negotiate about output line width
71 NAOP
= chr(9) # negotiate about output page size
72 NAOCRD
= chr(10) # negotiate about CR disposition
73 NAOHTS
= chr(11) # negotiate about horizontal tabstops
74 NAOHTD
= chr(12) # negotiate about horizontal tab disposition
75 NAOFFD
= chr(13) # negotiate about formfeed disposition
76 NAOVTS
= chr(14) # negotiate about vertical tab stops
77 NAOVTD
= chr(15) # negotiate about vertical tab disposition
78 NAOLFD
= chr(16) # negotiate about output LF disposition
79 XASCII
= chr(17) # extended ascii character set
80 LOGOUT
= chr(18) # force logout
81 BM
= chr(19) # byte macro
82 DET
= chr(20) # data entry terminal
83 SUPDUP
= chr(21) # supdup protocol
84 SUPDUPOUTPUT
= chr(22) # supdup output
85 SNDLOC
= chr(23) # send location
86 TTYPE
= chr(24) # terminal type
87 EOR
= chr(25) # end or record
88 TUID
= chr(26) # TACACS user identification
89 OUTMRK
= chr(27) # output marking
90 TTYLOC
= chr(28) # terminal location number
91 VT3270REGIME
= chr(29) # 3270 regime
92 X3PAD
= chr(30) # X.3 PAD
93 NAWS
= chr(31) # window size
94 TSPEED
= chr(32) # terminal speed
95 LFLOW
= chr(33) # remote flow control
96 LINEMODE
= chr(34) # Linemode option
97 XDISPLOC
= chr(35) # X Display Location
98 OLD_ENVIRON
= chr(36) # Old - Environment variables
99 AUTHENTICATION
= chr(37) # Authenticate
100 ENCRYPT
= chr(38) # Encryption option
101 NEW_ENVIRON
= chr(39) # New - Environment variables
102 # the following ones come from
103 # http://www.iana.org/assignments/telnet-options
104 # Unfortunately, that document does not assign identifiers
105 # to all of them, so we are making them up
106 TN3270E
= chr(40) # TN3270E
107 XAUTH
= chr(41) # XAUTH
108 CHARSET
= chr(42) # CHARSET
109 RSP
= chr(43) # Telnet Remote Serial Port
110 COM_PORT_OPTION
= chr(44) # Com Port Control Option
111 SUPPRESS_LOCAL_ECHO
= chr(45) # Telnet Suppress Local Echo
112 TLS
= chr(46) # Telnet Start TLS
113 KERMIT
= chr(47) # KERMIT
114 SEND_URL
= chr(48) # SEND-URL
115 FORWARD_X
= chr(49) # FORWARD_X
116 PRAGMA_LOGON
= chr(138) # TELOPT PRAGMA LOGON
117 SSPI_LOGON
= chr(139) # TELOPT SSPI LOGON
118 PRAGMA_HEARTBEAT
= chr(140) # TELOPT PRAGMA HEARTBEAT
119 EXOPL
= chr(255) # Extended-Options-List
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.
172 def __init__(self
, host
=None, port
=0):
175 When called without arguments, create an unconnected instance.
176 With a hostname argument, it connects the instance; a port
180 self
.debuglevel
= DEBUGLEVEL
188 self
.option_callback
= None
190 self
.open(host
, port
)
192 def open(self
, host
, port
=0):
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
210 self
.sock
= socket
.socket(af
, socktype
, proto
)
211 self
.sock
.connect(sa
)
212 except socket
.error
, msg
:
218 raise socket
.error
, msg
221 """Destructor -- close the connection."""
224 def msg(self
, msg
, *args
):
225 """Print a debug message, when the debug level is > 0.
227 If extra arguments are present, they are substituted in the
228 message using the standard string formatting operator.
231 if self
.debuglevel
> 0:
232 print 'Telnet(%s,%d):' % (self
.host
, self
.port
),
238 def set_debuglevel(self
, debuglevel
):
239 """Set the debug level.
241 The higher it is, the more debug output you get (on sys.stdout).
244 self
.debuglevel
= debuglevel
247 """Close the connection."""
253 def get_socket(self
):
254 """Return the socket object used internally."""
258 """Return the fileno() of the socket object used internally."""
259 return self
.sock
.fileno()
261 def write(self
, buffer):
262 """Write a string to the socket, doubling any IAC characters.
264 Can block if the connection is blocked. May raise
265 socket.error if the connection is closed.
269 buffer = buffer.replace(IAC
, IAC
+IAC
)
270 self
.msg("send %s", `
buffer`
)
271 self
.sock
.send(buffer)
273 def read_until(self
, match
, timeout
=None):
274 """Read until a given string is encountered or until timeout.
276 When no match is found, return whatever is available instead,
277 possibly the empty string. Raise EOFError if the connection
278 is closed and no cooked data is available.
283 i
= self
.cookedq
.find(match
)
286 buf
= self
.cookedq
[:i
]
287 self
.cookedq
= self
.cookedq
[i
:]
289 s_reply
= ([self
], [], [])
291 if timeout
is not None:
292 s_args
= s_args
+ (timeout
,)
293 while not self
.eof
and apply(select
.select
, s_args
) == s_reply
:
294 i
= max(0, len(self
.cookedq
)-n
)
297 i
= self
.cookedq
.find(match
, i
)
300 buf
= self
.cookedq
[:i
]
301 self
.cookedq
= self
.cookedq
[i
:]
303 return self
.read_very_lazy()
306 """Read all data until EOF; block until connection closed."""
316 """Read at least one byte of cooked data unless EOF is hit.
318 Return '' if EOF is hit. Block if no data is immediately
323 while not self
.cookedq
and not self
.eof
:
330 def read_very_eager(self
):
331 """Read everything that's possible without blocking in I/O (eager).
333 Raise EOFError if connection closed and no cooked data
334 available. Return '' if no cooked data available otherwise.
335 Don't block unless in the midst of an IAC sequence.
339 while not self
.eof
and self
.sock_avail():
342 return self
.read_very_lazy()
344 def read_eager(self
):
345 """Read readily available data.
347 Raise EOFError if connection closed and no cooked data
348 available. Return '' if no cooked data available otherwise.
349 Don't block unless in the midst of an IAC sequence.
353 while not self
.cookedq
and not self
.eof
and self
.sock_avail():
356 return self
.read_very_lazy()
359 """Process and return data that's already in the queues (lazy).
361 Raise EOFError if connection closed and no data available.
362 Return '' if no cooked data available otherwise. Don't block
363 unless in the midst of an IAC sequence.
367 return self
.read_very_lazy()
369 def read_very_lazy(self
):
370 """Return any data available in the cooked queue (very lazy).
372 Raise EOFError if connection closed and no data available.
373 Return '' if no cooked data available otherwise. Don't block.
378 if not buf
and self
.eof
and not self
.rawq
:
379 raise EOFError, 'telnet connection closed'
382 def set_option_negotiation_callback(self
, callback
):
383 """Provide a callback function called after each receipt of a telnet option."""
384 self
.option_callback
= callback
386 def process_rawq(self
):
387 """Transfer from raw queue to cooked queue.
389 Set self.eof when connection is closed. Don't block unless in
390 the midst of an IAC sequence.
396 c
= self
.rawq_getchar()
404 c
= self
.rawq_getchar()
407 elif c
in (DO
, DONT
):
408 opt
= self
.rawq_getchar()
409 self
.msg('IAC %s %d', c
== DO
and 'DO' or 'DONT', ord(opt
))
410 if self
.option_callback
:
411 self
.option_callback(self
.sock
, c
, opt
)
413 self
.sock
.send(IAC
+ WONT
+ opt
)
414 elif c
in (WILL
, WONT
):
415 opt
= self
.rawq_getchar()
416 self
.msg('IAC %s %d',
417 c
== WILL
and 'WILL' or 'WONT', ord(opt
))
418 if self
.option_callback
:
419 self
.option_callback(self
.sock
, c
, opt
)
421 self
.sock
.send(IAC
+ DONT
+ opt
)
423 self
.msg('IAC %d not recognized' % ord(opt
))
424 except EOFError: # raised by self.rawq_getchar()
426 self
.cookedq
= self
.cookedq
+ buf
428 def rawq_getchar(self
):
429 """Get next char from raw queue.
431 Block if no data is immediately available. Raise EOFError
432 when connection is closed.
439 c
= self
.rawq
[self
.irawq
]
440 self
.irawq
= self
.irawq
+ 1
441 if self
.irawq
>= len(self
.rawq
):
447 """Fill raw queue from exactly one recv() system call.
449 Block if no data is immediately available. Set self.eof when
450 connection is closed.
453 if self
.irawq
>= len(self
.rawq
):
456 # The buffer size should be fairly small so as to avoid quadratic
457 # behavior in process_rawq() above
458 buf
= self
.sock
.recv(50)
459 self
.msg("recv %s", `buf`
)
461 self
.rawq
= self
.rawq
+ buf
463 def sock_avail(self
):
464 """Test whether data is available on the socket."""
465 return select
.select([self
], [], [], 0) == ([self
], [], [])
468 """Interaction function, emulates a very dumb telnet client."""
469 if sys
.platform
== "win32":
473 rfd
, wfd
, xfd
= select
.select([self
, sys
.stdin
], [], [])
476 text
= self
.read_eager()
478 print '*** Connection closed by remote host ***'
481 sys
.stdout
.write(text
)
484 line
= sys
.stdin
.readline()
489 def mt_interact(self
):
490 """Multithreaded version of interact()."""
492 thread
.start_new_thread(self
.listener
, ())
494 line
= sys
.stdin
.readline()
500 """Helper for mt_interact() -- this executes in the other thread."""
503 data
= self
.read_eager()
505 print '*** Connection closed by remote host ***'
508 sys
.stdout
.write(data
)
512 def expect(self
, list, timeout
=None):
513 """Read until one from a list of a regular expressions matches.
515 The first argument is a list of regular expressions, either
516 compiled (re.RegexObject instances) or uncompiled (strings).
517 The optional second argument is a timeout, in seconds; default
520 Return a tuple of three items: the index in the list of the
521 first regular expression that matches; the match object
522 returned; and the text read up till and including the match.
524 If EOF is read and no text was read, raise EOFError.
525 Otherwise, when nothing matches, return (-1, None, text) where
526 text is the text received so far (may be the empty string if a
529 If a regular expression ends with a greedy match (e.g. '.*')
530 or if more than one expression can match the same input, the
531 results are undeterministic, and may depend on the I/O timing.
536 indices
= range(len(list))
538 if not hasattr(list[i
], "search"):
540 list[i
] = re
.compile(list[i
])
544 m
= list[i
].search(self
.cookedq
)
547 text
= self
.cookedq
[:e
]
548 self
.cookedq
= self
.cookedq
[e
:]
552 if timeout
is not None:
553 r
, w
, x
= select
.select([self
.fileno()], [], [], timeout
)
557 text
= self
.read_very_lazy()
558 if not text
and self
.eof
:
560 return (-1, None, text
)
564 """Test program for telnetlib.
566 Usage: python telnetlib.py [-d] ... [host [port]]
568 Default host is localhost; default port is 23.
572 while sys
.argv
[1:] and sys
.argv
[1] == '-d':
573 debuglevel
= debuglevel
+1
580 portstr
= sys
.argv
[2]
584 port
= socket
.getservbyname(portstr
, 'tcp')
586 tn
.set_debuglevel(debuglevel
)
591 if __name__
== '__main__':