#!/usr/local/bin/python

import os, string, sys
import ExpectPy

class Telnet:
  telnetprog = 'telnet'
  def __init__(self, hostname, user, password):
    self.hostname = hostname
    self.user = user
    self.passwd = password
    self._fp = ExpectPy.spawn(None, self.telnetprog, hostname)
    self._wait_for_connect()
  def _wait_for_connect(self):
    self._fp.expect(
      (ExpectPy.EXACT, "Escape character is '^]'.\r\n", None),
      (ExpectPy.GLOB, "*\r\n", lambda m, s=self._fp: s.cont())
    )

  # callbacks for expect clauses
  def _send_user(self, match):
    self._fp.send(self.user + '\r')
    self._fp.expect((ExpectPy.GLOB, "*\r\n", None))
    self._fp.cont()
  def _send_password(self, match):
    self._fp.send(self.passwd + '\r')
    self._fp.expect((ExpectPy.EXACT, "\r\n", None))

  def login(self, user=None, password=None):
    if user is not None:
      self.user = user
    if password is not None:
      self.passwd = password
    self._fp.expect(
      (ExpectPy.EXACT, "login: ", self._send_user),
      (ExpectPy.EXACT, "assword:", self._send_password)
    )
  def interact(self, tty=ExpectPy.tty_spawn_id):
    try:
      self._fp.interact(tty)
    except EOFError:
      pass

if __name__ == '__main__':
  hostname, user, passwd = 'northshore', 'arcege', 'DuMMy-56'
  telnet = Telnet(hostname, user, passwd)
  telnet.login()
  telnet.interact()

