Based on RFC 854: TELNET Protocol Specification, by J. Postel and
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write(b'guido\r\n')
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 a selector in order to wait until
more data is available. Note that in this case, read_eager() may return b''
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).
- timeout should be intrinsic to the connection object instead of an
option on one of the read calls only
from time import monotonic as _time
# Telnet protocol defaults
# Telnet protocol characters (don't change)
IAC = bytes([255]) # "Interpret As Command"
SE = bytes([240]) # Subnegotiation End
NOP = bytes([241]) # No Operation
DM = bytes([242]) # Data Mark
BRK = bytes([243]) # Break
IP = bytes([244]) # Interrupt process
AO = bytes([245]) # Abort output
AYT = bytes([246]) # Are You There
EC = bytes([247]) # Erase Character
EL = bytes([248]) # Erase Line
GA = bytes([249]) # Go Ahead
SB = bytes([250]) # Subnegotiation Begin
# Telnet protocol options code (don't change)
# These ones all come from arpa/telnet.h
BINARY = bytes([0]) # 8-bit data path
RCP = bytes([2]) # prepare to reconnect
SGA = bytes([3]) # suppress go ahead
NAMS = bytes([4]) # approximate message size
STATUS = bytes([5]) # give status
TM = bytes([6]) # timing mark
RCTE = bytes([7]) # remote controlled transmission and echo
NAOL = bytes([8]) # negotiate about output line width
NAOP = bytes([9]) # negotiate about output page size
NAOCRD = bytes([10]) # negotiate about CR disposition
NAOHTS = bytes([11]) # negotiate about horizontal tabstops
NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
NAOFFD = bytes([13]) # negotiate about formfeed disposition
NAOVTS = bytes([14]) # negotiate about vertical tab stops
NAOVTD = bytes([15]) # negotiate about vertical tab disposition
NAOLFD = bytes([16]) # negotiate about output LF disposition
XASCII = bytes([17]) # extended ascii character set
LOGOUT = bytes([18]) # force logout
BM = bytes([19]) # byte macro
DET = bytes([20]) # data entry terminal
SUPDUP = bytes([21]) # supdup protocol
SUPDUPOUTPUT = bytes([22]) # supdup output
SNDLOC = bytes([23]) # send location
TTYPE = bytes([24]) # terminal type
EOR = bytes([25]) # end or record
TUID = bytes([26]) # TACACS user identification
OUTMRK = bytes([27]) # output marking
TTYLOC = bytes([28]) # terminal location number
VT3270REGIME = bytes([29]) # 3270 regime
X3PAD = bytes([30]) # X.3 PAD
NAWS = bytes([31]) # window size
TSPEED = bytes([32]) # terminal speed
LFLOW = bytes([33]) # remote flow control
LINEMODE = bytes([34]) # Linemode option
XDISPLOC = bytes([35]) # X Display Location
OLD_ENVIRON = bytes([36]) # Old - Environment variables
AUTHENTICATION = bytes([37]) # Authenticate
ENCRYPT = bytes([38]) # Encryption option
NEW_ENVIRON = bytes([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 = bytes([40]) # TN3270E
XAUTH = bytes([41]) # XAUTH
CHARSET = bytes([42]) # CHARSET
RSP = bytes([43]) # Telnet Remote Serial Port
COM_PORT_OPTION = bytes([44]) # Com Port Control Option
SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
TLS = bytes([46]) # Telnet Start TLS
KERMIT = bytes([47]) # KERMIT
SEND_URL = bytes([48]) # SEND-URL
FORWARD_X = bytes([49]) # FORWARD_X
PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
EXOPL = bytes([255]) # Extended-Options-List
# poll/select have the advantage of not requiring any extra file descriptor,
# contrarily to epoll/kqueue (also, they require a single syscall).
if hasattr(selectors, 'PollSelector'):
_TelnetSelector = selectors.PollSelector
_TelnetSelector = selectors.SelectSelector
"""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
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
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 data until EOF; may block.
Read at least one byte or EOF; may block.
Read all data available already queued or on the socket,
Read either data already queued or some data available on the
socket, without blocking.
Read all data in the raw queue (processing it first), without
Reads all data in the cooked queue, without doing any socket
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.
def __init__(self, host=None, port=0,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; port number
and timeout are optional.
self.debuglevel = DEBUGLEVEL
self.iacseq = b'' # Buffer for IAC sequence.
self.sb = 0 # flag for SB and SE sequence.
self.option_callback = None
self.open(host, port, timeout)
def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
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.
sys.audit("telnetlib.Telnet.open", self, host, port)
self.sock = socket.create_connection((host, port), timeout)
"""Destructor -- close the connection."""
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.
print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
def set_debuglevel(self, debuglevel):
The higher it is, the more debug output you get (on sys.stdout).
self.debuglevel = debuglevel
"""Close the connection."""
"""Return the socket object used internally."""
"""Return the fileno() of the socket object used internally."""
return self.sock.fileno()
"""Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
OSError if the connection is closed.
buffer = buffer.replace(IAC, IAC+IAC)
sys.audit("telnetlib.Telnet.write", self, buffer)
self.msg("send %r", buffer)
self.sock.sendall(buffer)
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.
i = self.cookedq.find(match)
self.cookedq = self.cookedq[i:]
deadline = _time() + timeout
with _TelnetSelector() as selector:
selector.register(self, selectors.EVENT_READ)
if selector.select(timeout):
i = max(0, len(self.cookedq)-n)
i = self.cookedq.find(match, i)
self.cookedq = self.cookedq[i:]
timeout = deadline - _time()
return self.read_very_lazy()
"""Read all data until EOF; block until connection closed."""
"""Read at least one byte of cooked data unless EOF is hit.
Return b'' if EOF is hit. Block if no data is immediately
while not self.cookedq and not self.eof:
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 b'' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
while not self.eof and self.sock_avail():
return self.read_very_lazy()
"""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.
while not self.cookedq and not self.eof and self.sock_avail():
return self.read_very_lazy()
"""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.
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 b'' if no cooked data available otherwise. Don't block.
if not buf and self.eof and not self.rawq:
raise EOFError('telnet connection closed')
"""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.
def set_option_negotiation_callback(self, callback):
"""Provide a callback function called after each receipt of a telnet option."""
self.option_callback = callback
"""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[self.sb] = buf[self.sb] + c
elif len(self.iacseq) == 1:
# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
buf[self.sb] = buf[self.sb] + c
if c == SB: # SB ... SE start.
self.sbdataq = self.sbdataq + buf[1]
# Callback is supposed to look into
self.option_callback(self.sock, c, NOOPT)
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd == DO and 'DO' or 'DONT', ord(opt))
self.option_callback(self.sock, cmd, opt)
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
cmd == WILL and 'WILL' or 'WONT', ord(opt))
self.option_callback(self.sock, cmd, opt)
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = b'' # Reset on EOF
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1]
"""Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed.