#!/usr/bin/env python
"""TELNET client class.

Based on RFC 854: TELNET Protocol Specification, by J. Postel and
J. Reynolds

Example:

>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79)   # connect to finger port
>>> tn.write('guido\r\n')
>>> print tn.read_all()
Login       Name               TTY         Idle    When    Where
guido    Guido van Rossum      pts/2        <Dec  2 11:10> snag.cnri.reston..
 
>>>

Note that read_all() won't read until eof -- it just reads some data
-- but it guarantees to read at least one byte unless EOF is hit.

It is possible to pass a Telnet object to select.select() in order to
wait until more data is available.  Note that in this case,
read_eager() may return '' even if there was data on the socket,
because the protocol negotiation may have eaten the data.  This is why
EOFError is needed in some cases to distinguish between "no data" and
"connection closed" (since the socket also appears ready for reading
when it is closed).

Bugs:
- may hang when connection is slow in the middle of an IAC sequence

To do:
- option negotiation
- timeout should be intrinsic to the connection object instead of an
  option on one of the read calls only

Modifications:
1 Mar 2001  Author: Luke Kenneth Casson Leighton <lkcl@samba-tng.org>

TelnetBase - split Telnet into base class to allow other
"telnet-like" base classes to be transparently created.

For example, a TelnetPopen4 class that takes a command as
its... um... host argument (e.g. to ssh) which then behaves
exactly as the Telnet class does except it's ssh.   Or this:
TelnetPopen4("/bin/bash").

For example, a TelnetHTTP class that wraps HTTP requests,
and treats them as write commands, which allows you to perform
expect and read_until and friends on the HTTP response!

Or any other protocol.  Or, how about TelnetUnixDomainSocket()?

All of which will have exactly the same style of interface


22 Mar 2003  Author: Luke Kenneth Casson Leighton <lkcl@samba-tng.org>
             Copyright (C) 2001, 2002, 2003 - Luke Kenneth Casson Leighton

Split out (useful!) socket wrapping code into Expect, in expectlib.

Added in the TelnetPopen4 class and example usage (ssh).

"""


# Imported modules
import sys
import socket
import select
import string
from expectlib import Expect

__all__ = ["Telnet", "TelnetBase"]

# Tunable parameters
DEBUGLEVEL = 0

# Telnet protocol defaults
TELNET_PORT = 23

# Telnet protocol characters (don't change)
IAC  = chr(255) # "Interpret As Command"
DONT = chr(254)
DO   = chr(253)
WONT = chr(252)
WILL = chr(251)
theNULL = chr(0)

# Telnet protocol options code (don't change)
# These ones all come from arpa/telnet.h
BINARY = chr(0) # 8-bit data path
ECHO = chr(1) # echo
RCP = chr(2) # prepare to reconnect
SGA = chr(3) # suppress go ahead
NAMS = chr(4) # approximate message size
STATUS = chr(5) # give status
TM = chr(6) # timing mark
RCTE = chr(7) # remote controlled transmission and echo
NAOL = chr(8) # negotiate about output line width
NAOP = chr(9) # negotiate about output page size
NAOCRD = chr(10) # negotiate about CR disposition
NAOHTS = chr(11) # negotiate about horizontal tabstops
NAOHTD = chr(12) # negotiate about horizontal tab disposition
NAOFFD = chr(13) # negotiate about formfeed disposition
NAOVTS = chr(14) # negotiate about vertical tab stops
NAOVTD = chr(15) # negotiate about vertical tab disposition
NAOLFD = chr(16) # negotiate about output LF disposition
XASCII = chr(17) # extended ascii character set
LOGOUT = chr(18) # force logout
BM = chr(19) # byte macro
DET = chr(20) # data entry terminal
SUPDUP = chr(21) # supdup protocol
SUPDUPOUTPUT = chr(22) # supdup output
SNDLOC = chr(23) # send location
TTYPE = chr(24) # terminal type
EOR = chr(25) # end or record
TUID = chr(26) # TACACS user identification
OUTMRK = chr(27) # output marking
TTYLOC = chr(28) # terminal location number
VT3270REGIME = chr(29) # 3270 regime
X3PAD = chr(30) # X.3 PAD
NAWS = chr(31) # window size
TSPEED = chr(32) # terminal speed
LFLOW = chr(33) # remote flow control
LINEMODE = chr(34) # Linemode option
XDISPLOC = chr(35) # X Display Location
OLD_ENVIRON = chr(36) # Old - Environment variables
AUTHENTICATION = chr(37) # Authenticate
ENCRYPT = chr(38) # Encryption option
NEW_ENVIRON = chr(39) # New - Environment variables
# the following ones come from
# http://www.iana.org/assignments/telnet-options
# Unfortunately, that document does not assign identifiers
# to all of them, so we are making them up
TN3270E = chr(40) # TN3270E
XAUTH = chr(41) # XAUTH
CHARSET = chr(42) # CHARSET
RSP = chr(43) # Telnet Remote Serial Port
COM_PORT_OPTION = chr(44) # Com Port Control Option
SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
TLS = chr(46) # Telnet Start TLS
KERMIT = chr(47) # KERMIT
SEND_URL = chr(48) # SEND-URL
FORWARD_X = chr(49) # FORWARD_X
PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
EXOPL = chr(255) # Extended-Options-List

class TelnetBase(Expect):

    """TelnetBase interface class.

    An instance of this class represents a connection to something
	resembling a telnet server.  For example, a popen3 to a command
	such as ssh could be performed, or if you are feeling up to it,
	combine TelnetBase with HTTPConnection!
	
    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.

    """

    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.

        """
		
        Expect.__init__(self)

        self.debuglevel = DEBUGLEVEL
        self.host = host
        self.port = port
        self.sock = None
        if host:
            self.open(host, port)

    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.

        """
        raise NotImplementedError

    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.

        """
        if self.debuglevel > 0:
            print 'Telnet(%s,%d):' % (self.host, self.port),
            if args:
                print msg % args
            else:
                print msg

    def set_debuglevel(self, debuglevel):
        """Set the debug level.

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

        """
        self.debuglevel = debuglevel

class Telnet(TelnetBase):

    """Telnet interface class.

    An instance of this class represents a connection to a telnet
    server.  It provides socket-based functions that automatically
	handle IAC sequences.  It also looks like a socket class.

	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.

    """

    def __init__(self, host=None, port=0):
		
		TelnetBase.__init__(self, host, port)
		self.option_callback = None

    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.

        """
        self.eof = 0
        if not port:
            port = TELNET_PORT
        self.host = host
        self.port = port
        msg = "getaddrinfo returns an empty list"
        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                self.sock.connect(sa)
            except socket.error, msg:
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg

    def __del__(self):
        """Destructor -- close the connection."""
        self.close()

    def close(self):
        """Close the connection."""
        if self.sock:
            self.sock.close()
        self.sock = 0
        self.eof = 1

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

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

    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.

        """
        if IAC in buffer:
            buffer = buffer.replace(IAC, IAC+IAC)
        self.msg("send %s", `buffer`)
        self.sock.sendall(buffer)

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

    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.

        """
        buf = ''
        try:
            while self.rawq:
                c = self.rawq_getchar()
                if c == theNULL:
                    continue
                if c == "\021":
                    continue
                if c != IAC:
                    buf = buf + c
                    continue
                c = self.rawq_getchar()
                if c == IAC:
                    buf = buf + c
                elif c in (DO, DONT):
                    opt = self.rawq_getchar()
                    self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(opt))
                    if self.option_callback:
                        self.option_callback(self.sock, c, opt)
                    else:
                        self.sock.sendall(IAC + WONT + opt)
                elif c in (WILL, WONT):
                    opt = self.rawq_getchar()
                    self.msg('IAC %s %d',
                             c == WILL and 'WILL' or 'WONT', ord(opt))
                    if self.option_callback:
                        self.option_callback(self.sock, c, opt)
                    else:
                        self.sock.sendall(IAC + DONT + opt)
                else:
                    self.msg('IAC %d not recognized' % ord(c))
        except EOFError: # raised by self.rawq_getchar()
            pass
        self.cookedq = self.cookedq + buf

    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.

        """
        if self.irawq >= len(self.rawq):
            self.rawq = ''
            self.irawq = 0
        # The buffer size should be fairly small so as to avoid quadratic
        # behavior in process_rawq() above
        buf = self.sock.recv(50)
        self.msg("recv %s", `buf`)
        self.eof = (not buf)
        self.rawq = self.rawq + buf

    def select(self, timeout):
        """Test whether data is available on the socket."""
        return select.select([self.fileno()], [], [], timeout)

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

import sys
import os

class TelnetPopen4(TelnetBase):

	"""Popen4 telnet interface class.

	An instance of this class represents a connection to a command.

	Don't try to reopen an already connected instance.

	"""

	def open(self, host, port=0):
		"""Connect to a command.

		Don't try to reopen an already connected instance.

		"""
		self.eof = 0
		self.host = host
		#self.w, self.r, self.e = os.popen3(host)
		self.w, self.r = os.popen4(host)
		self.e = None

	def __del__(self):
		"""Destructor -- close the connection."""
		if self.r:
			self.r.close()
		if self.w:
			self.w.close()
		if self.e:
			self.e.close()

	def close(self):
		"""Close the connection."""
		if self.r:
			self.r.close()
		if self.w:
			self.w.close()
		if self.e:
			self.e.close()
		self.sock = 0
		self.eof = 1

	def get_socket(self):
		"""Return the read socket object used internally.  whoops."""
		return self.r

	def fileno(self):
		"""Return the fileno() of the socket object used internally."""
		return self.get_socket().fileno()

	def write(self, buffer):
		"""Write a string to the socket.

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

		"""
		self.msg("send %s", `buffer`)
		self.w.write(buffer)
		self.w.flush()

	def process_rawq(self):
		"""Transfer from raw queue to cooked queue.

		Set self.eof when connection is closed.  

		"""
		buf = ''
		try:
			while self.rawq:
				buf = buf + self.rawq_getchar()
		except EOFError: # raised by self.rawq_getchar()
			pass
		self.cookedq = self.cookedq + buf

	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.

		"""
		if self.irawq >= len(self.rawq):
			self.rawq = ''
			self.irawq = 0
		# The buffer size should be fairly small so as to avoid quadratic
		# behavior in process_rawq() above
		buf = os.read(self.fileno(), 50)
		self.msg("read %s", `buf`)
		self.eof = (not buf)
		self.rawq = self.rawq + buf

	def select(self, timeout):
		"""Test whether data is available on the socket."""
		return select.select([self.fileno()], [], [], timeout)

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

def ssh_test():
	"""	little example usage of TelnetPopen4 using ssh and a ls -al
		command over it.

		the trouble with ssh is of course that if you get a password
		prompt, you're hosed: it's not possible to trap the system
		call that requests a password.

		if you _do_ want to avoid getting the password prompt,
		download the ssh sources, patch it to accept user:pass@hostname
		syntax!
		
		horribly insecure, i know, but better than attempting to
		use telnet to manage remote boxes.
	"""
	
	from time import sleep

	cmd = "ssh -v localhost"
	t = TelnetPopen4(cmd)
	print t.read_some()
	t.write("ls -al\n")
	while 1:
		sleep(0.1)
		print t.read_some()

def popen4_test():
    """Test program for TelnetPopen4.

    Usage: python Popen4lib.py [-d] command and parameters

	e.g. python popen3lib.py ls -al
	e.g. python popen3lib.py ssh -v localhost

    """
    debuglevel = 0
    while sys.argv[1:] and sys.argv[1] == '-d':
        debuglevel = debuglevel+1
        del sys.argv[1]
    tn = TelnetPopen4()
    tn.set_debuglevel(debuglevel)
    cmd = ' '.join(sys.argv[1:])
    print cmd
    tn.open(cmd)
    tn.mt_interact()
    tn.close()

def telnet_test():
    """Test program for telnetlib.

    Usage: python telnetlib.py [-d] ... [host [port]]

    Default host is localhost; default port is 23.

    """
    debuglevel = 0
    while sys.argv[1:] and sys.argv[1] == '-d':
        debuglevel = debuglevel+1
        del sys.argv[1]
    host = 'localhost'
    if sys.argv[1:]:
        host = sys.argv[1]
    port = 0
    if sys.argv[2:]:
        portstr = sys.argv[2]
        try:
            port = int(portstr)
        except ValueError:
            port = socket.getservbyname(portstr, 'tcp')
    tn = Telnet()
    tn.set_debuglevel(debuglevel)
    tn.open(host, port)
    tn.interact()
    tn.close()

if __name__ == '__main__':
    #telnet_test()
    popen4_test()
