Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
Telnet Class Reference

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 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
 

Data Fields

 debuglevel
 
 host
 
 port
 
 sock
 
 rawq
 
 irawq
 
 cookedq
 
 eof
 
 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.

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 (DO/DONT/WILL/WONT), option)
    No other action is done afterwards by telnetlib.

Definition at line 121 of file telnetlib.py.

Constructor & Destructor Documentation

def __init__ (   self,
  host = None,
  port = 0 
)
Constructor.

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

Definition at line 172 of file telnetlib.py.

173  def __init__(self, host=None, port=0):
174  """Constructor.
175 
176  When called without arguments, create an unconnected instance.
177  With a hostname argument, it connects the instance; a port
178  number is optional.
179 
180  """
181  self.debuglevel = DEBUGLEVEL
182  self.host = host
183  self.port = port
184  self.sock = None
185  self.rawq = ''
186  self.irawq = 0
187  self.cookedq = ''
188  self.eof = 0
189  self.option_callback = None
190  if host:
191  self.open(host, port)
def __del__ (   self)

Member Function Documentation

def close (   self)
Close the connection.

Definition at line 247 of file telnetlib.py.

References Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, POP3.sock, FTP.sock, NNTP.sock, Telnet.sock, SMTP.sock, HTTPConnection.sock, and HTTPSConnection.sock.

248  def close(self):
249  """Close the connection."""
250  if self.sock:
251  self.sock.close()
252  self.sock = 0
253  self.eof = 1
def 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 513 of file telnetlib.py.

References Telnet.cookedq, Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, _fileobject.fileno(), Telnet.fileno(), TCPServer.fileno(), file_wrapper.fileno(), addbase.fileno, Telnet.fill_rawq(), Telnet.process_rawq(), Telnet.read_very_lazy(), and pre.search().

514  def expect(self, list, timeout=None):
515  """Read until one from a list of a regular expressions matches.
516 
517  The first argument is a list of regular expressions, either
518  compiled (re.RegexObject instances) or uncompiled (strings).
519  The optional second argument is a timeout, in seconds; default
520  is no timeout.
521 
522  Return a tuple of three items: the index in the list of the
523  first regular expression that matches; the match object
524  returned; and the text read up till and including the match.
525 
526  If EOF is read and no text was read, raise EOFError.
527  Otherwise, when nothing matches, return (-1, None, text) where
528  text is the text received so far (may be the empty string if a
529  timeout happened).
530 
531  If a regular expression ends with a greedy match (e.g. '.*')
532  or if more than one expression can match the same input, the
533  results are undeterministic, and may depend on the I/O timing.
534 
535  """
536  re = None
537  list = list[:]
538  indices = range(len(list))
539  for i in indices:
540  if not hasattr(list[i], "search"):
541  if not re: import re
542  list[i] = re.compile(list[i])
543  while 1:
544  self.process_rawq()
545  for i in indices:
546  m = list[i].search(self.cookedq)
547  if m:
548  e = m.end()
549  text = self.cookedq[:e]
550  self.cookedq = self.cookedq[e:]
551  return (i, m, text)
552  if self.eof:
553  break
554  if timeout is not None:
555  r, w, x = select.select([self.fileno()], [], [], timeout)
556  if not r:
557  break
558  self.fill_rawq()
559  text = self.read_very_lazy()
560  if not text and self.eof:
561  raise EOFError
562  return (-1, None, text)
563 
def fileno (   self)
Return the fileno() of the socket object used internally.

Definition at line 258 of file telnetlib.py.

259  def fileno(self):
260  """Return the fileno() of the socket object used internally."""
261  return self.sock.fileno()
def fill_rawq (   self)
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 447 of file telnetlib.py.

References Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.irawq, NetrcParseError.msg, GetoptError.msg, Error.msg, HTTPResponse.msg, HTTPError.msg, Telnet.msg(), and Telnet.rawq.

448  def fill_rawq(self):
449  """Fill raw queue from exactly one recv() system call.
450 
451  Block if no data is immediately available. Set self.eof when
452  connection is closed.
453 
454  """
455  if self.irawq >= len(self.rawq):
456  self.rawq = ''
457  self.irawq = 0
458  # The buffer size should be fairly small so as to avoid quadratic
459  # behavior in process_rawq() above
460  buf = self.sock.recv(50)
461  self.msg("recv %s", `buf`)
462  self.eof = (not buf)
463  self.rawq = self.rawq + buf
def get_socket (   self)
Return the socket object used internally.

Definition at line 254 of file telnetlib.py.

References POP3.sock, FTP.sock, NNTP.sock, Telnet.sock, SMTP.sock, HTTPConnection.sock, and HTTPSConnection.sock.

255  def get_socket(self):
256  """Return the socket object used internally."""
257  return self.sock
def interact (   self)
Interaction function, emulates a very dumb telnet client.

Definition at line 468 of file telnetlib.py.

References Telnet.mt_interact(), Telnet.read_eager(), Devnull.write(), Pickler.write, openrsrc.write(), _Hqxcoderengine.write(), StreamWriter.write(), GzipFile.write(), StringIO.write(), _Rlecoderengine.write(), InteractiveInterpreter.write(), _fileobject.write(), BinHex.write(), Telnet.write(), StreamReaderWriter.write(), ConfigParser.write(), _SpoofOut.write(), StreamRecoder.write(), Marshaller.write, and file_wrapper.write.

469  def interact(self):
470  """Interaction function, emulates a very dumb telnet client."""
471  if sys.platform == "win32":
472  self.mt_interact()
473  return
474  while 1:
475  rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
476  if self in rfd:
477  try:
478  text = self.read_eager()
479  except EOFError:
480  print '*** Connection closed by remote host ***'
481  break
482  if text:
483  sys.stdout.write(text)
484  sys.stdout.flush()
485  if sys.stdin in rfd:
486  line = sys.stdin.readline()
487  if not line:
488  break
489  self.write(line)
def listener (   self)
Helper for mt_interact() -- this executes in the other thread.

Definition at line 500 of file telnetlib.py.

References Telnet.read_eager().

501  def listener(self):
502  """Helper for mt_interact() -- this executes in the other thread."""
503  while 1:
504  try:
505  data = self.read_eager()
506  except EOFError:
507  print '*** Connection closed by remote host ***'
508  return
509  if data:
510  sys.stdout.write(data)
511  else:
512  sys.stdout.flush()
def 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.

Definition at line 225 of file telnetlib.py.

References HTTPResponse.debuglevel, Telnet.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, HTTP.debuglevel, POP3.host, FTP.host, NNTP.host, Telnet.host, HTTPConnection.host, POP3.port, FTP.port, NNTP.port, Telnet.port, and HTTPConnection.port.

226  def msg(self, msg, *args):
227  """Print a debug message, when the debug level is > 0.
228 
229  If extra arguments are present, they are substituted in the
230  message using the standard string formatting operator.
231 
232  """
233  if self.debuglevel > 0:
234  print 'Telnet(%s,%d):' % (self.host, self.port),
235  if args:
236  print msg % args
237  else:
238  print msg
def mt_interact (   self)
Multithreaded version of interact().

Definition at line 490 of file telnetlib.py.

References Telnet.listener(), Devnull.write(), Pickler.write, openrsrc.write(), _Hqxcoderengine.write(), StreamWriter.write(), GzipFile.write(), StringIO.write(), _Rlecoderengine.write(), InteractiveInterpreter.write(), _fileobject.write(), BinHex.write(), Telnet.write(), StreamReaderWriter.write(), ConfigParser.write(), _SpoofOut.write(), StreamRecoder.write(), Marshaller.write, and file_wrapper.write.

491  def mt_interact(self):
492  """Multithreaded version of interact()."""
493  import thread
494  thread.start_new_thread(self.listener, ())
495  while 1:
496  line = sys.stdin.readline()
497  if not line:
498  break
499  self.write(line)
def open (   self,
  host,
  port = 0 
)
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 192 of file telnetlib.py.

References Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, POP3.host, FTP.host, NNTP.host, Telnet.host, HTTPConnection.host, POP3.port, FTP.port, NNTP.port, Telnet.port, HTTPConnection.port, POP3.sock, FTP.sock, NNTP.sock, Telnet.sock, SMTP.sock, HTTPConnection.sock, HTTPSConnection.sock, and socket.socket().

193  def open(self, host, port=0):
194  """Connect to a host.
195 
196  The optional second argument is the port number, which
197  defaults to the standard telnet port (23).
198 
199  Don't try to reopen an already connected instance.
200 
201  """
202  self.eof = 0
203  if not port:
204  port = TELNET_PORT
205  self.host = host
206  self.port = port
207  msg = "getaddrinfo returns an empty list"
208  for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
209  af, socktype, proto, canonname, sa = res
210  try:
211  self.sock = socket.socket(af, socktype, proto)
212  self.sock.connect(sa)
213  except socket.error, msg:
214  if self.sock:
215  self.sock.close()
216  self.sock = None
217  continue
218  break
219  if not self.sock:
220  raise socket.error, msg
def process_rawq (   self)
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 387 of file telnetlib.py.

References Telnet.cookedq, NetrcParseError.msg, GetoptError.msg, Error.msg, HTTPResponse.msg, HTTPError.msg, Telnet.msg(), Telnet.option_callback, Telnet.rawq, Telnet.rawq_getchar(), POP3.sock, FTP.sock, NNTP.sock, Telnet.sock, SMTP.sock, HTTPConnection.sock, and HTTPSConnection.sock.

388  def process_rawq(self):
389  """Transfer from raw queue to cooked queue.
390 
391  Set self.eof when connection is closed. Don't block unless in
392  the midst of an IAC sequence.
393 
394  """
395  buf = ''
396  try:
397  while self.rawq:
398  c = self.rawq_getchar()
399  if c == theNULL:
400  continue
401  if c == "\021":
402  continue
403  if c != IAC:
404  buf = buf + c
405  continue
406  c = self.rawq_getchar()
407  if c == IAC:
408  buf = buf + c
409  elif c in (DO, DONT):
410  opt = self.rawq_getchar()
411  self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(opt))
412  if self.option_callback:
413  self.option_callback(self.sock, c, opt)
414  else:
415  self.sock.sendall(IAC + WONT + opt)
416  elif c in (WILL, WONT):
417  opt = self.rawq_getchar()
418  self.msg('IAC %s %d',
419  c == WILL and 'WILL' or 'WONT', ord(opt))
420  if self.option_callback:
421  self.option_callback(self.sock, c, opt)
422  else:
423  self.sock.sendall(IAC + DONT + opt)
424  else:
425  self.msg('IAC %d not recognized' % ord(opt))
426  except EOFError: # raised by self.rawq_getchar()
427  pass
428  self.cookedq = self.cookedq + buf
def rawq_getchar (   self)
Get next char from raw queue.

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

Definition at line 429 of file telnetlib.py.

References Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.fill_rawq(), Telnet.irawq, and Telnet.rawq.

430  def rawq_getchar(self):
431  """Get next char from raw queue.
432 
433  Block if no data is immediately available. Raise EOFError
434  when connection is closed.
435 
436  """
437  if not self.rawq:
438  self.fill_rawq()
439  if self.eof:
440  raise EOFError
441  c = self.rawq[self.irawq]
442  self.irawq = self.irawq + 1
443  if self.irawq >= len(self.rawq):
444  self.rawq = ''
445  self.irawq = 0
446  return c
def read_all (   self)
Read all data until EOF; block until connection closed.

Definition at line 306 of file telnetlib.py.

References Telnet.cookedq, Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.fill_rawq(), and Telnet.process_rawq().

307  def read_all(self):
308  """Read all data until EOF; block until connection closed."""
309  self.process_rawq()
310  while not self.eof:
311  self.fill_rawq()
312  self.process_rawq()
313  buf = self.cookedq
314  self.cookedq = ''
315  return buf
def read_eager (   self)
Read readily available data.

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

Definition at line 345 of file telnetlib.py.

References Telnet.cookedq, Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.fill_rawq(), Telnet.process_rawq(), Telnet.read_very_lazy(), and Telnet.sock_avail().

346  def read_eager(self):
347  """Read readily available data.
348 
349  Raise EOFError if connection closed and no cooked data
350  available. Return '' if no cooked data available otherwise.
351  Don't block unless in the midst of an IAC sequence.
352 
353  """
354  self.process_rawq()
355  while not self.cookedq and not self.eof and self.sock_avail():
356  self.fill_rawq()
357  self.process_rawq()
358  return self.read_very_lazy()
def read_lazy (   self)
Process and return data that's already in the queues (lazy).

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

Definition at line 359 of file telnetlib.py.

References Telnet.process_rawq(), and Telnet.read_very_lazy().

360  def read_lazy(self):
361  """Process and return data that's already in the queues (lazy).
362 
363  Raise EOFError if connection closed and no data available.
364  Return '' if no cooked data available otherwise. Don't block
365  unless in the midst of an IAC sequence.
366 
367  """
368  self.process_rawq()
369  return self.read_very_lazy()
def read_some (   self)
Read at least one byte of cooked data unless EOF is hit.

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

Definition at line 316 of file telnetlib.py.

References Telnet.cookedq, Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.fill_rawq(), and Telnet.process_rawq().

317  def read_some(self):
318  """Read at least one byte of cooked data unless EOF is hit.
319 
320  Return '' if EOF is hit. Block if no data is immediately
321  available.
322 
323  """
324  self.process_rawq()
325  while not self.cookedq and not self.eof:
326  self.fill_rawq()
327  self.process_rawq()
328  buf = self.cookedq
329  self.cookedq = ''
330  return buf
def 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 274 of file telnetlib.py.

References Telnet.cookedq, Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.fill_rawq(), sre_parse.max, Telnet.process_rawq(), and Telnet.read_very_lazy().

275  def read_until(self, match, timeout=None):
276  """Read until a given string is encountered or until timeout.
277 
278  When no match is found, return whatever is available instead,
279  possibly the empty string. Raise EOFError if the connection
280  is closed and no cooked data is available.
281 
282  """
283  n = len(match)
284  self.process_rawq()
285  i = self.cookedq.find(match)
286  if i >= 0:
287  i = i+n
288  buf = self.cookedq[:i]
289  self.cookedq = self.cookedq[i:]
290  return buf
291  s_reply = ([self], [], [])
292  s_args = s_reply
293  if timeout is not None:
294  s_args = s_args + (timeout,)
295  while not self.eof and apply(select.select, s_args) == s_reply:
296  i = max(0, len(self.cookedq)-n)
297  self.fill_rawq()
298  self.process_rawq()
299  i = self.cookedq.find(match, i)
300  if i >= 0:
301  i = i+n
302  buf = self.cookedq[:i]
303  self.cookedq = self.cookedq[i:]
304  return buf
305  return self.read_very_lazy()
def read_very_eager (   self)
Read everything that's possible without blocking in I/O (eager).

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

Definition at line 331 of file telnetlib.py.

References Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, Telnet.fill_rawq(), Telnet.process_rawq(), Telnet.read_very_lazy(), and Telnet.sock_avail().

332  def read_very_eager(self):
333  """Read everything that's possible without blocking in I/O (eager).
334 
335  Raise EOFError if connection closed and no cooked data
336  available. Return '' if no cooked data available otherwise.
337  Don't block unless in the midst of an IAC sequence.
338 
339  """
340  self.process_rawq()
341  while not self.eof and self.sock_avail():
342  self.fill_rawq()
343  self.process_rawq()
344  return self.read_very_lazy()
def read_very_lazy (   self)
Return any data available in the cooked queue (very lazy).

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

Definition at line 370 of file telnetlib.py.

References Telnet.cookedq, Telnet.eof, _Hqxdecoderengine.eof, _Rledecoderengine.eof, and Telnet.rawq.

371  def read_very_lazy(self):
372  """Return any data available in the cooked queue (very lazy).
373 
374  Raise EOFError if connection closed and no data available.
375  Return '' if no cooked data available otherwise. Don't block.
376 
377  """
378  buf = self.cookedq
379  self.cookedq = ''
380  if not buf and self.eof and not self.rawq:
381  raise EOFError, 'telnet connection closed'
382  return buf
def set_debuglevel (   self,
  debuglevel 
)
Set the debug level.

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

Definition at line 239 of file telnetlib.py.

References HTTPResponse.debuglevel, Telnet.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, and HTTP.debuglevel.

240  def set_debuglevel(self, debuglevel):
241  """Set the debug level.
242 
243  The higher it is, the more debug output you get (on sys.stdout).
244 
245  """
246  self.debuglevel = debuglevel
def set_option_negotiation_callback (   self,
  callback 
)
Provide a callback function called after each receipt of a telnet option.

Definition at line 383 of file telnetlib.py.

References Telnet.option_callback.

384  def set_option_negotiation_callback(self, callback):
385  """Provide a callback function called after each receipt of a telnet option."""
386  self.option_callback = callback
def sock_avail (   self)
Test whether data is available on the socket.

Definition at line 464 of file telnetlib.py.

465  def sock_avail(self):
466  """Test whether data is available on the socket."""
467  return select.select([self], [], [], 0) == ([self], [], [])
def 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 262 of file telnetlib.py.

References NetrcParseError.msg, GetoptError.msg, Error.msg, HTTPResponse.msg, HTTPError.msg, and Telnet.msg().

263  def write(self, buffer):
264  """Write a string to the socket, doubling any IAC characters.
265 
266  Can block if the connection is blocked. May raise
267  socket.error if the connection is closed.
268 
269  """
270  if IAC in buffer:
271  buffer = buffer.replace(IAC, IAC+IAC)
272  self.msg("send %s", `buffer`)
273  self.sock.sendall(buffer)

Field Documentation

cookedq

Definition at line 186 of file telnetlib.py.

debuglevel

Definition at line 180 of file telnetlib.py.

eof

Definition at line 187 of file telnetlib.py.

host

Definition at line 181 of file telnetlib.py.

irawq

Definition at line 185 of file telnetlib.py.

option_callback

Definition at line 188 of file telnetlib.py.

port

Definition at line 182 of file telnetlib.py.

rawq

Definition at line 184 of file telnetlib.py.

sock

Definition at line 183 of file telnetlib.py.


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