Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes
telnetlib.Telnet Class Reference
Inheritance diagram for telnetlib.Telnet:
Inheritance graph
[legend]

List of all members.

Public Member Functions

def __init__
def open
def __del__
def msg
def set_debuglevel
def close
def get_socket
def fileno
def write
def read_until
def read_all
def read_some
def read_very_eager
def read_eager
def read_lazy
def read_very_lazy
def read_sb_data
def set_option_negotiation_callback
def process_rawq
def rawq_getchar
def fill_rawq
def sock_avail
def interact
def mt_interact
def listener
def expect

Public Attributes

 debuglevel
 host
 port
 timeout
 sock
 rawq
 irawq
 cookedq
 eof
 iacseq
 sb
 sbdataq
 option_callback

Detailed Description

Telnet interface class.

An instance of this class represents a connection to a telnet
server.  The instance is initially not connected; the open()
method must be used to establish a connection.  Alternatively, the
host name and optional port number can be passed to the
constructor, too.

Don't try to reopen an already connected instance.

This class has many read_*() methods.  Note that some of them
raise EOFError when the end of the connection is read, because
they can return an empty string for other reasons.  See the
individual doc strings.

read_until(expected, [timeout])
    Read until the expected string has been seen, or a timeout is
    hit (default is no timeout); may block.

read_all()
    Read all data until EOF; may block.

read_some()
    Read at least one byte or EOF; may block.

read_very_eager()
    Read all data available already queued or on the socket,
    without blocking.

read_eager()
    Read either data already queued or some data available on the
    socket, without blocking.

read_lazy()
    Read all data in the raw queue (processing it first), without
    doing any socket I/O.

read_very_lazy()
    Reads all data in the cooked queue, without doing any socket
    I/O.

read_sb_data()
    Reads available data between SB ... SE sequence. Don't block.

set_option_negotiation_callback(callback)
    Each time a telnet option is read on the input flow, this callback
    (if set) is called with the following parameters :
    callback(telnet socket, command, option)
        option will be chr(0) when there is no option.
    No other action is done afterwards by telnetlib.

Definition at line 132 of file telnetlib.py.


Constructor & Destructor Documentation

def telnetlib.Telnet.__init__ (   self,
  host = None,
  port = 0,
  timeout = socket._GLOBAL_DEFAULT_TIMEOUT 
)
Constructor.

When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; port number
and timeout are optional.

Definition at line 188 of file telnetlib.py.

00188 
00189                  timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
00190         """Constructor.
00191 
00192         When called without arguments, create an unconnected instance.
00193         With a hostname argument, it connects the instance; port number
00194         and timeout are optional.
00195         """
00196         self.debuglevel = DEBUGLEVEL
00197         self.host = host
00198         self.port = port
00199         self.timeout = timeout
00200         self.sock = None
00201         self.rawq = b''
00202         self.irawq = 0
00203         self.cookedq = b''
00204         self.eof = 0
00205         self.iacseq = b'' # Buffer for IAC sequence.
00206         self.sb = 0 # flag for SB and SE sequence.
00207         self.sbdataq = b''
00208         self.option_callback = None
00209         if host is not None:
00210             self.open(host, port, timeout)

Here is the caller graph for this function:

def telnetlib.Telnet.__del__ (   self)
Destructor -- close the connection.

Definition at line 227 of file telnetlib.py.

00227 
00228     def __del__(self):
00229         """Destructor -- close the connection."""
00230         self.close()


Member Function Documentation

def telnetlib.Telnet.close (   self)
Close the connection.

Reimplemented in test.test_telnetlib.TelnetAlike.

Definition at line 253 of file telnetlib.py.

00253 
00254     def close(self):
00255         """Close the connection."""
00256         if self.sock:
00257             self.sock.close()
00258         self.sock = 0
00259         self.eof = 1
00260         self.iacseq = b''
00261         self.sb = 0

Here is the caller graph for this function:

def telnetlib.Telnet.expect (   self,
  list,
  timeout = None 
)
Read until one from a list of a regular expressions matches.

The first argument is a list of regular expressions, either
compiled (re.RegexObject instances) or uncompiled (strings).
The optional second argument is a timeout, in seconds; default
is no timeout.

Return a tuple of three items: the index in the list of the
first regular expression that matches; the match object
returned; and the text read up till and including the match.

If EOF is read and no text was read, raise EOFError.
Otherwise, when nothing matches, return (-1, None, text) where
text is the text received so far (may be the empty string if a
timeout happened).

If a regular expression ends with a greedy match (e.g. '.*')
or if more than one expression can match the same input, the
results are undeterministic, and may depend on the I/O timing.

Definition at line 570 of file telnetlib.py.

00570 
00571     def expect(self, list, timeout=None):
00572         """Read until one from a list of a regular expressions matches.
00573 
00574         The first argument is a list of regular expressions, either
00575         compiled (re.RegexObject instances) or uncompiled (strings).
00576         The optional second argument is a timeout, in seconds; default
00577         is no timeout.
00578 
00579         Return a tuple of three items: the index in the list of the
00580         first regular expression that matches; the match object
00581         returned; and the text read up till and including the match.
00582 
00583         If EOF is read and no text was read, raise EOFError.
00584         Otherwise, when nothing matches, return (-1, None, text) where
00585         text is the text received so far (may be the empty string if a
00586         timeout happened).
00587 
00588         If a regular expression ends with a greedy match (e.g. '.*')
00589         or if more than one expression can match the same input, the
00590         results are undeterministic, and may depend on the I/O timing.
00591 
00592         """
00593         re = None
00594         list = list[:]
00595         indices = range(len(list))
00596         for i in indices:
00597             if not hasattr(list[i], "search"):
00598                 if not re: import re
00599                 list[i] = re.compile(list[i])
00600         if timeout is not None:
00601             from time import time
00602             time_start = time()
00603         while 1:
00604             self.process_rawq()
00605             for i in indices:
00606                 m = list[i].search(self.cookedq)
00607                 if m:
00608                     e = m.end()
00609                     text = self.cookedq[:e]
00610                     self.cookedq = self.cookedq[e:]
00611                     return (i, m, text)
00612             if self.eof:
00613                 break
00614             if timeout is not None:
00615                 elapsed = time() - time_start
00616                 if elapsed >= timeout:
00617                     break
00618                 s_args = ([self.fileno()], [], [], timeout-elapsed)
00619                 r, w, x = select.select(*s_args)
00620                 if not r:
00621                     break
00622             self.fill_rawq()
00623         text = self.read_very_lazy()
00624         if not text and self.eof:
00625             raise EOFError
00626         return (-1, None, text)
00627 

Here is the call graph for this function:

def telnetlib.Telnet.fileno (   self)
Return the fileno() of the socket object used internally.

Reimplemented in test.test_telnetlib.TelnetAlike.

Definition at line 266 of file telnetlib.py.

00266 
00267     def fileno(self):
00268         """Return the fileno() of the socket object used internally."""
00269         return self.sock.fileno()

Here is the caller graph for this function:

Fill raw queue from exactly one recv() system call.

Block if no data is immediately available.  Set self.eof when
connection is closed.

Definition at line 504 of file telnetlib.py.

00504 
00505     def fill_rawq(self):
00506         """Fill raw queue from exactly one recv() system call.
00507 
00508         Block if no data is immediately available.  Set self.eof when
00509         connection is closed.
00510 
00511         """
00512         if self.irawq >= len(self.rawq):
00513             self.rawq = b''
00514             self.irawq = 0
00515         # The buffer size should be fairly small so as to avoid quadratic
00516         # behavior in process_rawq() above
00517         buf = self.sock.recv(50)
00518         self.msg("recv %r", buf)
00519         self.eof = (not buf)
00520         self.rawq = self.rawq + buf

Here is the call graph for this function:

Here is the caller graph for this function:

Return the socket object used internally.

Definition at line 262 of file telnetlib.py.

00262 
00263     def get_socket(self):
00264         """Return the socket object used internally."""
00265         return self.sock

def telnetlib.Telnet.interact (   self)
Interaction function, emulates a very dumb telnet client.

Definition at line 525 of file telnetlib.py.

00525 
00526     def interact(self):
00527         """Interaction function, emulates a very dumb telnet client."""
00528         if sys.platform == "win32":
00529             self.mt_interact()
00530             return
00531         while 1:
00532             rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
00533             if self in rfd:
00534                 try:
00535                     text = self.read_eager()
00536                 except EOFError:
00537                     print('*** Connection closed by remote host ***')
00538                     break
00539                 if text:
00540                     sys.stdout.write(text.decode('ascii'))
00541                     sys.stdout.flush()
00542             if sys.stdin in rfd:
00543                 line = sys.stdin.readline().encode('ascii')
00544                 if not line:
00545                     break
00546                 self.write(line)

Here is the call graph for this function:

def telnetlib.Telnet.listener (   self)
Helper for mt_interact() -- this executes in the other thread.

Definition at line 557 of file telnetlib.py.

00557 
00558     def listener(self):
00559         """Helper for mt_interact() -- this executes in the other thread."""
00560         while 1:
00561             try:
00562                 data = self.read_eager()
00563             except EOFError:
00564                 print('*** Connection closed by remote host ***')
00565                 return
00566             if data:
00567                 sys.stdout.write(data.decode('ascii'))
00568             else:
00569                 sys.stdout.flush()

Here is the call graph for this function:

Here is the caller graph for this function:

def telnetlib.Telnet.msg (   self,
  msg,
  args 
)
Print a debug message, when the debug level is > 0.

If extra arguments are present, they are substituted in the
message using the standard string formatting operator.

Reimplemented in test.test_telnetlib.TelnetAlike.

Definition at line 231 of file telnetlib.py.

00231 
00232     def msg(self, msg, *args):
00233         """Print a debug message, when the debug level is > 0.
00234 
00235         If extra arguments are present, they are substituted in the
00236         message using the standard string formatting operator.
00237 
00238         """
00239         if self.debuglevel > 0:
00240             print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
00241             if args:
00242                 print(msg % args)
00243             else:
00244                 print(msg)

Here is the caller graph for this function:

Multithreaded version of interact().

Definition at line 547 of file telnetlib.py.

00547 
00548     def mt_interact(self):
00549         """Multithreaded version of interact()."""
00550         import _thread
00551         _thread.start_new_thread(self.listener, ())
00552         while 1:
00553             line = sys.stdin.readline()
00554             if not line:
00555                 break
00556             self.write(line.encode('ascii'))

Here is the call graph for this function:

Here is the caller graph for this function:

def telnetlib.Telnet.open (   self,
  host,
  port = 0,
  timeout = socket._GLOBAL_DEFAULT_TIMEOUT 
)
Connect to a host.

The optional second argument is the port number, which
defaults to the standard telnet port (23).

Don't try to reopen an already connected instance.

Definition at line 211 of file telnetlib.py.

00211 
00212     def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
00213         """Connect to a host.
00214 
00215         The optional second argument is the port number, which
00216         defaults to the standard telnet port (23).
00217 
00218         Don't try to reopen an already connected instance.
00219         """
00220         self.eof = 0
00221         if not port:
00222             port = TELNET_PORT
00223         self.host = host
00224         self.port = port
00225         self.timeout = timeout
00226         self.sock = socket.create_connection((host, port), timeout)

Here is the call graph for this function:

Transfer from raw queue to cooked queue.

Set self.eof when connection is closed.  Don't block unless in
the midst of an IAC sequence.

Definition at line 414 of file telnetlib.py.

00414 
00415     def process_rawq(self):
00416         """Transfer from raw queue to cooked queue.
00417 
00418         Set self.eof when connection is closed.  Don't block unless in
00419         the midst of an IAC sequence.
00420 
00421         """
00422         buf = [b'', b'']
00423         try:
00424             while self.rawq:
00425                 c = self.rawq_getchar()
00426                 if not self.iacseq:
00427                     if c == theNULL:
00428                         continue
00429                     if c == b"\021":
00430                         continue
00431                     if c != IAC:
00432                         buf[self.sb] = buf[self.sb] + c
00433                         continue
00434                     else:
00435                         self.iacseq += c
00436                 elif len(self.iacseq) == 1:
00437                     # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
00438                     if c in (DO, DONT, WILL, WONT):
00439                         self.iacseq += c
00440                         continue
00441 
00442                     self.iacseq = b''
00443                     if c == IAC:
00444                         buf[self.sb] = buf[self.sb] + c
00445                     else:
00446                         if c == SB: # SB ... SE start.
00447                             self.sb = 1
00448                             self.sbdataq = b''
00449                         elif c == SE:
00450                             self.sb = 0
00451                             self.sbdataq = self.sbdataq + buf[1]
00452                             buf[1] = b''
00453                         if self.option_callback:
00454                             # Callback is supposed to look into
00455                             # the sbdataq
00456                             self.option_callback(self.sock, c, NOOPT)
00457                         else:
00458                             # We can't offer automatic processing of
00459                             # suboptions. Alas, we should not get any
00460                             # unless we did a WILL/DO before.
00461                             self.msg('IAC %d not recognized' % ord(c))
00462                 elif len(self.iacseq) == 2:
00463                     cmd = self.iacseq[1:2]
00464                     self.iacseq = b''
00465                     opt = c
00466                     if cmd in (DO, DONT):
00467                         self.msg('IAC %s %d',
00468                             cmd == DO and 'DO' or 'DONT', ord(opt))
00469                         if self.option_callback:
00470                             self.option_callback(self.sock, cmd, opt)
00471                         else:
00472                             self.sock.sendall(IAC + WONT + opt)
00473                     elif cmd in (WILL, WONT):
00474                         self.msg('IAC %s %d',
00475                             cmd == WILL and 'WILL' or 'WONT', ord(opt))
00476                         if self.option_callback:
00477                             self.option_callback(self.sock, cmd, opt)
00478                         else:
00479                             self.sock.sendall(IAC + DONT + opt)
00480         except EOFError: # raised by self.rawq_getchar()
00481             self.iacseq = b'' # Reset on EOF
00482             self.sb = 0
00483             pass
00484         self.cookedq = self.cookedq + buf[0]
00485         self.sbdataq = self.sbdataq + buf[1]

Here is the call graph for this function:

Here is the caller graph for this function:

Get next char from raw queue.

Block if no data is immediately available.  Raise EOFError
when connection is closed.

Definition at line 486 of file telnetlib.py.

00486 
00487     def rawq_getchar(self):
00488         """Get next char from raw queue.
00489 
00490         Block if no data is immediately available.  Raise EOFError
00491         when connection is closed.
00492 
00493         """
00494         if not self.rawq:
00495             self.fill_rawq()
00496             if self.eof:
00497                 raise EOFError
00498         c = self.rawq[self.irawq:self.irawq+1]
00499         self.irawq = self.irawq + 1
00500         if self.irawq >= len(self.rawq):
00501             self.rawq = b''
00502             self.irawq = 0
00503         return c

Here is the call graph for this function:

Here is the caller graph for this function:

def telnetlib.Telnet.read_all (   self)
Read all data until EOF; block until connection closed.

Definition at line 321 of file telnetlib.py.

00321 
00322     def read_all(self):
00323         """Read all data until EOF; block until connection closed."""
00324         self.process_rawq()
00325         while not self.eof:
00326             self.fill_rawq()
00327             self.process_rawq()
00328         buf = self.cookedq
00329         self.cookedq = b''
00330         return buf

Here is the call graph for this function:

Read readily available data.

Raise EOFError if connection closed and no cooked data
available.  Return b'' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.

Definition at line 360 of file telnetlib.py.

00360 
00361     def read_eager(self):
00362         """Read readily available data.
00363 
00364         Raise EOFError if connection closed and no cooked data
00365         available.  Return b'' if no cooked data available otherwise.
00366         Don't block unless in the midst of an IAC sequence.
00367 
00368         """
00369         self.process_rawq()
00370         while not self.cookedq and not self.eof and self.sock_avail():
00371             self.fill_rawq()
00372             self.process_rawq()
00373         return self.read_very_lazy()

Here is the call graph for this function:

Here is the caller graph for this function:

Process and return data that's already in the queues (lazy).

Raise EOFError if connection closed and no data available.
Return b'' if no cooked data available otherwise.  Don't block
unless in the midst of an IAC sequence.

Definition at line 374 of file telnetlib.py.

00374 
00375     def read_lazy(self):
00376         """Process and return data that's already in the queues (lazy).
00377 
00378         Raise EOFError if connection closed and no data available.
00379         Return b'' if no cooked data available otherwise.  Don't block
00380         unless in the midst of an IAC sequence.
00381 
00382         """
00383         self.process_rawq()
00384         return self.read_very_lazy()

Here is the call graph for this function:

Return any data available in the SB ... SE queue.

Return b'' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block.

Definition at line 398 of file telnetlib.py.

00398 
00399     def read_sb_data(self):
00400         """Return any data available in the SB ... SE queue.
00401 
00402         Return b'' if no SB ... SE available. Should only be called
00403         after seeing a SB or SE command. When a new SB command is
00404         found, old unread SB data will be discarded. Don't block.
00405 
00406         """
00407         buf = self.sbdataq
00408         self.sbdataq = b''
00409         return buf

Read at least one byte of cooked data unless EOF is hit.

Return b'' if EOF is hit.  Block if no data is immediately
available.

Definition at line 331 of file telnetlib.py.

00331 
00332     def read_some(self):
00333         """Read at least one byte of cooked data unless EOF is hit.
00334 
00335         Return b'' if EOF is hit.  Block if no data is immediately
00336         available.
00337 
00338         """
00339         self.process_rawq()
00340         while not self.cookedq and not self.eof:
00341             self.fill_rawq()
00342             self.process_rawq()
00343         buf = self.cookedq
00344         self.cookedq = b''
00345         return buf

Here is the call graph for this function:

def telnetlib.Telnet.read_until (   self,
  match,
  timeout = None 
)
Read until a given string is encountered or until timeout.

When no match is found, return whatever is available instead,
possibly the empty string.  Raise EOFError if the connection
is closed and no cooked data is available.

Definition at line 282 of file telnetlib.py.

00282 
00283     def read_until(self, match, timeout=None):
00284         """Read until a given string is encountered or until timeout.
00285 
00286         When no match is found, return whatever is available instead,
00287         possibly the empty string.  Raise EOFError if the connection
00288         is closed and no cooked data is available.
00289 
00290         """
00291         n = len(match)
00292         self.process_rawq()
00293         i = self.cookedq.find(match)
00294         if i >= 0:
00295             i = i+n
00296             buf = self.cookedq[:i]
00297             self.cookedq = self.cookedq[i:]
00298             return buf
00299         s_reply = ([self], [], [])
00300         s_args = s_reply
00301         if timeout is not None:
00302             s_args = s_args + (timeout,)
00303             from time import time
00304             time_start = time()
00305         while not self.eof and select.select(*s_args) == s_reply:
00306             i = max(0, len(self.cookedq)-n)
00307             self.fill_rawq()
00308             self.process_rawq()
00309             i = self.cookedq.find(match, i)
00310             if i >= 0:
00311                 i = i+n
00312                 buf = self.cookedq[:i]
00313                 self.cookedq = self.cookedq[i:]
00314                 return buf
00315             if timeout is not None:
00316                 elapsed = time() - time_start
00317                 if elapsed >= timeout:
00318                     break
00319                 s_args = s_reply + (timeout-elapsed,)
00320         return self.read_very_lazy()

Here is the call graph for this function:

Read everything that's possible without blocking in I/O (eager).

Raise EOFError if connection closed and no cooked data
available.  Return b'' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.

Definition at line 346 of file telnetlib.py.

00346 
00347     def read_very_eager(self):
00348         """Read everything that's possible without blocking in I/O (eager).
00349 
00350         Raise EOFError if connection closed and no cooked data
00351         available.  Return b'' if no cooked data available otherwise.
00352         Don't block unless in the midst of an IAC sequence.
00353 
00354         """
00355         self.process_rawq()
00356         while not self.eof and self.sock_avail():
00357             self.fill_rawq()
00358             self.process_rawq()
00359         return self.read_very_lazy()

Here is the call graph for this function:

Return any data available in the cooked queue (very lazy).

Raise EOFError if connection closed and no data available.
Return b'' if no cooked data available otherwise.  Don't block.

Definition at line 385 of file telnetlib.py.

00385 
00386     def read_very_lazy(self):
00387         """Return any data available in the cooked queue (very lazy).
00388 
00389         Raise EOFError if connection closed and no data available.
00390         Return b'' if no cooked data available otherwise.  Don't block.
00391 
00392         """
00393         buf = self.cookedq
00394         self.cookedq = b''
00395         if not buf and self.eof and not self.rawq:
00396             raise EOFError('telnet connection closed')
00397         return buf

Here is the caller graph for this function:

def telnetlib.Telnet.set_debuglevel (   self,
  debuglevel 
)
Set the debug level.

The higher it is, the more debug output you get (on sys.stdout).

Definition at line 245 of file telnetlib.py.

00245 
00246     def set_debuglevel(self, debuglevel):
00247         """Set the debug level.
00248 
00249         The higher it is, the more debug output you get (on sys.stdout).
00250 
00251         """
00252         self.debuglevel = debuglevel

def telnetlib.Telnet.set_option_negotiation_callback (   self,
  callback 
)
Provide a callback function called after each receipt of a telnet option.

Definition at line 410 of file telnetlib.py.

00410 
00411     def set_option_negotiation_callback(self, callback):
00412         """Provide a callback function called after each receipt of a telnet option."""
00413         self.option_callback = callback

Test whether data is available on the socket.

Reimplemented in test.test_telnetlib.TelnetAlike.

Definition at line 521 of file telnetlib.py.

00521 
00522     def sock_avail(self):
00523         """Test whether data is available on the socket."""
00524         return select.select([self], [], [], 0) == ([self], [], [])

Here is the caller graph for this function:

def telnetlib.Telnet.write (   self,
  buffer 
)
Write a string to the socket, doubling any IAC characters.

Can block if the connection is blocked.  May raise
socket.error if the connection is closed.

Definition at line 270 of file telnetlib.py.

00270 
00271     def write(self, buffer):
00272         """Write a string to the socket, doubling any IAC characters.
00273 
00274         Can block if the connection is blocked.  May raise
00275         socket.error if the connection is closed.
00276 
00277         """
00278         if IAC in buffer:
00279             buffer = buffer.replace(IAC, IAC+IAC)
00280         self.msg("send %r", buffer)
00281         self.sock.sendall(buffer)

Here is the call graph for this function:


Member Data Documentation

Definition at line 202 of file telnetlib.py.

Definition at line 195 of file telnetlib.py.

Definition at line 203 of file telnetlib.py.

Definition at line 196 of file telnetlib.py.

Definition at line 204 of file telnetlib.py.

Definition at line 201 of file telnetlib.py.

Definition at line 207 of file telnetlib.py.

Definition at line 197 of file telnetlib.py.

Definition at line 200 of file telnetlib.py.

Definition at line 205 of file telnetlib.py.

Definition at line 206 of file telnetlib.py.

Definition at line 199 of file telnetlib.py.

Definition at line 198 of file telnetlib.py.


The documentation for this class was generated from the following file: