Search code examples
pythontelnetlib

another TypeError: a bytes-like object is required, not 'str'


I'm a complete newbie in Python, but I have been programming for fun in (Liberty-)Basic since about 1980.

Using Python 3.5.2 I was testing this script:

import time, telnetlib

host    = "dxc.ve7cc.net"
port    = 23
timeout = 9999

try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.read_until("login: ")
    session.write("on0xxx\n")
    output = session.read_some()
    while output:
        print (output)
        time.sleep(0.1)  # let the buffer fill up a bit
        output = session.read_some()

Can anyone tell me why I get the TypeError: a bytes-like object is required, not 'str' and how I can solve it?


Solution

  • In Python 3 (but not in Python 2), str and bytes are distinct types that can't be mixed. You can't write a str directly to a socket; you have to use bytes. Simply prefix the string literal with b to make it a bytes literal.

    session.write(b"on0xxx\n")