Victor Stinner's patch to make telnetlib use bytes 3725

This commit is contained in:
Benjamin Peterson 2008-10-15 20:54:24 +00:00
parent 33b6450d23
commit 3de7fb86fc
3 changed files with 109 additions and 107 deletions

View File

@ -225,14 +225,14 @@ A simple example illustrating typical use::
tn = telnetlib.Telnet(HOST) tn = telnetlib.Telnet(HOST)
tn.read_until("login: ") tn.read_until(b"login: ")
tn.write(user + "\n") tn.write(user.encode('ascii') + b"\n")
if password: if password:
tn.read_until("Password: ") tn.read_until(b"Password: ")
tn.write(password + "\n") tn.write(password.encode('ascii') + b"\n")
tn.write("ls\n") tn.write(b"ls\n")
tn.write("exit\n") tn.write(b"exit\n")
print(tn.read_all()) print(tn.read_all())

View File

@ -7,7 +7,7 @@ Example:
>>> from telnetlib import Telnet >>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port >>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write('guido\r\n') >>> tn.write(b'guido\r\n')
>>> print(tn.read_all()) >>> print(tn.read_all())
Login Name TTY Idle When Where Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston.. guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
@ -19,7 +19,7 @@ Note that read_all() won't read until eof -- it just reads some data
It is possible to pass a Telnet object to select.select() in order to 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, wait until more data is available. Note that in this case,
read_eager() may return '' even if there was data on the socket, 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 because the protocol negotiation may have eaten the data. This is why
EOFError is needed in some cases to distinguish between "no data" and EOFError is needed in some cases to distinguish between "no data" and
"connection closed" (since the socket also appears ready for reading "connection closed" (since the socket also appears ready for reading
@ -47,87 +47,87 @@ DEBUGLEVEL = 0
TELNET_PORT = 23 TELNET_PORT = 23
# Telnet protocol characters (don't change) # Telnet protocol characters (don't change)
IAC = chr(255) # "Interpret As Command" IAC = 255 # "Interpret As Command"
DONT = chr(254) DONT = 254
DO = chr(253) DO = 253
WONT = chr(252) WONT = 252
WILL = chr(251) WILL = 251
theNULL = chr(0) theNULL = 0
SE = chr(240) # Subnegotiation End SE = 240 # Subnegotiation End
NOP = chr(241) # No Operation NOP = 241 # No Operation
DM = chr(242) # Data Mark DM = 242 # Data Mark
BRK = chr(243) # Break BRK = 243 # Break
IP = chr(244) # Interrupt process IP = 244 # Interrupt process
AO = chr(245) # Abort output AO = 245 # Abort output
AYT = chr(246) # Are You There AYT = 246 # Are You There
EC = chr(247) # Erase Character EC = 247 # Erase Character
EL = chr(248) # Erase Line EL = 248 # Erase Line
GA = chr(249) # Go Ahead GA = 249 # Go Ahead
SB = chr(250) # Subnegotiation Begin SB = 250 # Subnegotiation Begin
# Telnet protocol options code (don't change) # Telnet protocol options code (don't change)
# These ones all come from arpa/telnet.h # These ones all come from arpa/telnet.h
BINARY = chr(0) # 8-bit data path BINARY = 0 # 8-bit data path
ECHO = chr(1) # echo ECHO = 1 # echo
RCP = chr(2) # prepare to reconnect RCP = 2 # prepare to reconnect
SGA = chr(3) # suppress go ahead SGA = 3 # suppress go ahead
NAMS = chr(4) # approximate message size NAMS = 4 # approximate message size
STATUS = chr(5) # give status STATUS = 5 # give status
TM = chr(6) # timing mark TM = 6 # timing mark
RCTE = chr(7) # remote controlled transmission and echo RCTE = 7 # remote controlled transmission and echo
NAOL = chr(8) # negotiate about output line width NAOL = 8 # negotiate about output line width
NAOP = chr(9) # negotiate about output page size NAOP = 9 # negotiate about output page size
NAOCRD = chr(10) # negotiate about CR disposition NAOCRD = 10 # negotiate about CR disposition
NAOHTS = chr(11) # negotiate about horizontal tabstops NAOHTS = 11 # negotiate about horizontal tabstops
NAOHTD = chr(12) # negotiate about horizontal tab disposition NAOHTD = 12 # negotiate about horizontal tab disposition
NAOFFD = chr(13) # negotiate about formfeed disposition NAOFFD = 13 # negotiate about formfeed disposition
NAOVTS = chr(14) # negotiate about vertical tab stops NAOVTS = 14 # negotiate about vertical tab stops
NAOVTD = chr(15) # negotiate about vertical tab disposition NAOVTD = 15 # negotiate about vertical tab disposition
NAOLFD = chr(16) # negotiate about output LF disposition NAOLFD = 16 # negotiate about output LF disposition
XASCII = chr(17) # extended ascii character set XASCII = 17 # extended ascii character set
LOGOUT = chr(18) # force logout LOGOUT = 18 # force logout
BM = chr(19) # byte macro BM = 19 # byte macro
DET = chr(20) # data entry terminal DET = 20 # data entry terminal
SUPDUP = chr(21) # supdup protocol SUPDUP = 21 # supdup protocol
SUPDUPOUTPUT = chr(22) # supdup output SUPDUPOUTPUT = 22 # supdup output
SNDLOC = chr(23) # send location SNDLOC = 23 # send location
TTYPE = chr(24) # terminal type TTYPE = 24 # terminal type
EOR = chr(25) # end or record EOR = 25 # end or record
TUID = chr(26) # TACACS user identification TUID = 26 # TACACS user identification
OUTMRK = chr(27) # output marking OUTMRK = 27 # output marking
TTYLOC = chr(28) # terminal location number TTYLOC = 28 # terminal location number
VT3270REGIME = chr(29) # 3270 regime VT3270REGIME = 29 # 3270 regime
X3PAD = chr(30) # X.3 PAD X3PAD = 30 # X.3 PAD
NAWS = chr(31) # window size NAWS = 31 # window size
TSPEED = chr(32) # terminal speed TSPEED = 32 # terminal speed
LFLOW = chr(33) # remote flow control LFLOW = 33 # remote flow control
LINEMODE = chr(34) # Linemode option LINEMODE = 34 # Linemode option
XDISPLOC = chr(35) # X Display Location XDISPLOC = 35 # X Display Location
OLD_ENVIRON = chr(36) # Old - Environment variables OLD_ENVIRON = 36 # Old - Environment variables
AUTHENTICATION = chr(37) # Authenticate AUTHENTICATION = 37 # Authenticate
ENCRYPT = chr(38) # Encryption option ENCRYPT = 38 # Encryption option
NEW_ENVIRON = chr(39) # New - Environment variables NEW_ENVIRON = 39 # New - Environment variables
# the following ones come from # the following ones come from
# http://www.iana.org/assignments/telnet-options # http://www.iana.org/assignments/telnet-options
# Unfortunately, that document does not assign identifiers # Unfortunately, that document does not assign identifiers
# to all of them, so we are making them up # to all of them, so we are making them up
TN3270E = chr(40) # TN3270E TN3270E = 40 # TN3270E
XAUTH = chr(41) # XAUTH XAUTH = 41 # XAUTH
CHARSET = chr(42) # CHARSET CHARSET = 42 # CHARSET
RSP = chr(43) # Telnet Remote Serial Port RSP = 43 # Telnet Remote Serial Port
COM_PORT_OPTION = chr(44) # Com Port Control Option COM_PORT_OPTION = 44 # Com Port Control Option
SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo SUPPRESS_LOCAL_ECHO = 45 # Telnet Suppress Local Echo
TLS = chr(46) # Telnet Start TLS TLS = 46 # Telnet Start TLS
KERMIT = chr(47) # KERMIT KERMIT = 47 # KERMIT
SEND_URL = chr(48) # SEND-URL SEND_URL = 48 # SEND-URL
FORWARD_X = chr(49) # FORWARD_X FORWARD_X = 49 # FORWARD_X
PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON PRAGMA_LOGON = 138 # TELOPT PRAGMA LOGON
SSPI_LOGON = chr(139) # TELOPT SSPI LOGON SSPI_LOGON = 139 # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT PRAGMA_HEARTBEAT = 140 # TELOPT PRAGMA HEARTBEAT
EXOPL = chr(255) # Extended-Options-List EXOPL = 255 # Extended-Options-List
NOOPT = chr(0) NOOPT = 0
class Telnet: class Telnet:
@ -197,13 +197,13 @@ class Telnet:
self.port = port self.port = port
self.timeout = timeout self.timeout = timeout
self.sock = None self.sock = None
self.rawq = '' self.rawq = b''
self.irawq = 0 self.irawq = 0
self.cookedq = '' self.cookedq = b''
self.eof = 0 self.eof = 0
self.iacseq = '' # Buffer for IAC sequence. self.iacseq = b'' # Buffer for IAC sequence.
self.sb = 0 # flag for SB and SE sequence. self.sb = 0 # flag for SB and SE sequence.
self.sbdataq = '' self.sbdataq = b''
self.option_callback = None self.option_callback = None
if host is not None: if host is not None:
self.open(host, port, timeout) self.open(host, port, timeout)
@ -256,7 +256,7 @@ class Telnet:
self.sock.close() self.sock.close()
self.sock = 0 self.sock = 0
self.eof = 1 self.eof = 1
self.iacseq = '' self.iacseq = b''
self.sb = 0 self.sb = 0
def get_socket(self): def get_socket(self):
@ -325,13 +325,13 @@ class Telnet:
self.fill_rawq() self.fill_rawq()
self.process_rawq() self.process_rawq()
buf = self.cookedq buf = self.cookedq
self.cookedq = '' self.cookedq = b''
return buf return buf
def read_some(self): def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit. """Read at least one byte of cooked data unless EOF is hit.
Return '' if EOF is hit. Block if no data is immediately Return b'' if EOF is hit. Block if no data is immediately
available. available.
""" """
@ -340,14 +340,14 @@ class Telnet:
self.fill_rawq() self.fill_rawq()
self.process_rawq() self.process_rawq()
buf = self.cookedq buf = self.cookedq
self.cookedq = '' self.cookedq = b''
return buf return buf
def read_very_eager(self): def read_very_eager(self):
"""Read everything that's possible without blocking in I/O (eager). """Read everything that's possible without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise. available. Return b'' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence. Don't block unless in the midst of an IAC sequence.
""" """
@ -361,7 +361,7 @@ class Telnet:
"""Read readily available data. """Read readily available data.
Raise EOFError if connection closed and no cooked data Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise. available. Return b'' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence. Don't block unless in the midst of an IAC sequence.
""" """
@ -375,7 +375,7 @@ class Telnet:
"""Process and return data that's already in the queues (lazy). """Process and return data that's already in the queues (lazy).
Raise EOFError if connection closed and no data available. Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block Return b'' if no cooked data available otherwise. Don't block
unless in the midst of an IAC sequence. unless in the midst of an IAC sequence.
""" """
@ -386,11 +386,11 @@ class Telnet:
"""Return any data available in the cooked queue (very lazy). """Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available. Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block. Return b'' if no cooked data available otherwise. Don't block.
""" """
buf = self.cookedq buf = self.cookedq
self.cookedq = '' self.cookedq = b''
if not buf and self.eof and not self.rawq: if not buf and self.eof and not self.rawq:
raise EOFError('telnet connection closed') raise EOFError('telnet connection closed')
return buf return buf
@ -398,13 +398,13 @@ class Telnet:
def read_sb_data(self): def read_sb_data(self):
"""Return any data available in the SB ... SE queue. """Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called Return b'' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block. found, old unread SB data will be discarded. Don't block.
""" """
buf = self.sbdataq buf = self.sbdataq
self.sbdataq = '' self.sbdataq = b''
return buf return buf
def set_option_negotiation_callback(self, callback): def set_option_negotiation_callback(self, callback):
@ -418,14 +418,14 @@ class Telnet:
the midst of an IAC sequence. the midst of an IAC sequence.
""" """
buf = ['', ''] buf = [b'', b'']
try: try:
while self.rawq: while self.rawq:
c = self.rawq_getchar() c = self.rawq_getchar()
if not self.iacseq: if not self.iacseq:
if c == theNULL: if c == theNULL:
continue continue
if c == "\021": if c == b"\021":
continue continue
if c != IAC: if c != IAC:
buf[self.sb] = buf[self.sb] + c buf[self.sb] = buf[self.sb] + c
@ -438,17 +438,17 @@ class Telnet:
self.iacseq += c self.iacseq += c
continue continue
self.iacseq = '' self.iacseq = b''
if c == IAC: if c == IAC:
buf[self.sb] = buf[self.sb] + c buf[self.sb] = buf[self.sb] + c
else: else:
if c == SB: # SB ... SE start. if c == SB: # SB ... SE start.
self.sb = 1 self.sb = 1
self.sbdataq = '' self.sbdataq = b''
elif c == SE: elif c == SE:
self.sb = 0 self.sb = 0
self.sbdataq = self.sbdataq + buf[1] self.sbdataq = self.sbdataq + buf[1]
buf[1] = '' buf[1] = b''
if self.option_callback: if self.option_callback:
# Callback is supposed to look into # Callback is supposed to look into
# the sbdataq # the sbdataq
@ -460,7 +460,7 @@ class Telnet:
self.msg('IAC %d not recognized' % ord(c)) self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2: elif len(self.iacseq) == 2:
cmd = self.iacseq[1] cmd = self.iacseq[1]
self.iacseq = '' self.iacseq = b''
opt = c opt = c
if cmd in (DO, DONT): if cmd in (DO, DONT):
self.msg('IAC %s %d', self.msg('IAC %s %d',
@ -477,7 +477,7 @@ class Telnet:
else: else:
self.sock.sendall(IAC + DONT + opt) self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar() except EOFError: # raised by self.rawq_getchar()
self.iacseq = '' # Reset on EOF self.iacseq = b'' # Reset on EOF
self.sb = 0 self.sb = 0
pass pass
self.cookedq = self.cookedq + buf[0] self.cookedq = self.cookedq + buf[0]
@ -494,10 +494,10 @@ class Telnet:
self.fill_rawq() self.fill_rawq()
if self.eof: if self.eof:
raise EOFError raise EOFError
c = self.rawq[self.irawq] c = self.rawq[self.irawq:self.irawq+1]
self.irawq = self.irawq + 1 self.irawq = self.irawq + 1
if self.irawq >= len(self.rawq): if self.irawq >= len(self.rawq):
self.rawq = '' self.rawq = b''
self.irawq = 0 self.irawq = 0
return c return c
@ -509,7 +509,7 @@ class Telnet:
""" """
if self.irawq >= len(self.rawq): if self.irawq >= len(self.rawq):
self.rawq = '' self.rawq = b''
self.irawq = 0 self.irawq = 0
# The buffer size should be fairly small so as to avoid quadratic # The buffer size should be fairly small so as to avoid quadratic
# behavior in process_rawq() above # behavior in process_rawq() above
@ -536,10 +536,10 @@ class Telnet:
print('*** Connection closed by remote host ***') print('*** Connection closed by remote host ***')
break break
if text: if text:
sys.stdout.write(text) sys.stdout.write(text.decode('ascii'))
sys.stdout.flush() sys.stdout.flush()
if sys.stdin in rfd: if sys.stdin in rfd:
line = sys.stdin.readline() line = sys.stdin.readline().encode('ascii')
if not line: if not line:
break break
self.write(line) self.write(line)

View File

@ -31,6 +31,8 @@ Core and Builtins
Library Library
------- -------
- telnetlib now works completely in bytes.
- Issue #4072: Restore build_py_2to3. - Issue #4072: Restore build_py_2to3.
- Issue #4014: Don't claim that Python has an Alpha release status, in addition - Issue #4014: Don't claim that Python has an Alpha release status, in addition