telnetlib.rst 7.21 KB

:mod:`telnetlib` --- Telnet client

The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the Telnet protocol. See RFC 854 for details about the protocol. In addition, it provides symbolic constants for the protocol characters (see below), and for the telnet options. The symbolic names of the telnet options follow the definitions in arpa/telnet.h, with the leading TELOPT_ removed. For symbolic names of options which are traditionally not included in arpa/telnet.h, see the module source itself.

The symbolic constants for the telnet commands are: IAC, DONT, DO, WONT, WILL, SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP (Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).

:class:`Telnet` represents a connection to a Telnet server. The instance is initially not connected by default; the :meth:`open` method must be used to establish a connection. Alternatively, the host name and optional port number can be passed to the constructor, to, in which case the connection to the server will be established before the constructor returns. The optional timeout parameter specifies a timeout in seconds for the connection attempt (if not specified, or passed as None, the global default timeout setting will be used).

Do not reopen an already connected instance.

This class has many :meth:`read_\*` methods. Note that some of them raise :exc:`EOFError` when the end of the connection is read, because they can return an empty string for other reasons. See the individual descriptions below.

Telnet Objects

:class:`Telnet` instances have the following methods:

Telnet Example

A simple example illustrating typical use:

import getpass
import sys
import telnetlib

def raw_input(prompt):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    return sys.stdin.readline()

HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")

print(tn.read_all())