Search code examples
pythontelnet

Telnet and Encoding in Python


This question is probably simple but so far I have not been able to find a solution anywhere. Basically, the following code is supposed to connect to a host, take a command, and print everything the host returns.

import telnetlib
import time

HOST = input("IP Address: ")
tn = telnetlib.Telnet(HOST, port = 23, timeout = 20)
time.sleep(10)
command = input("Enter command: ")
command.encode('utf-8')
tn.write(b"\n".join(command))
ret1 = tn.read_eager()
print(ret1)

print("Success!")
tn.close()

However, no matter what I try I keep on getting the same error:

C:\Python34>call python34 telnet_test.py
IP Address: 10.20.249.64
Enter command: 001 rq version
Traceback (most recent call last):
  File "telnet_test.py", line 9, in <module>
    tn.write(b"\n".join(command))
TypeError: sequence item 0: expected a bytes-like object, str found

I've tried other solutions based on similar questions I looked up but none of them seemed to work specifically here, I always end up getting the same error.


Solution

  • I'm assuming you're using Python 2 and not 3. I didn't mess about with any sort of encoding and it worked. Basically, my code was as follows:

    HOST = input("IP Address: ")
    tn = telnetlib.Telnet(HOST, port = 23, timeout = 20)
    time.sleep(10)
    command = input("Enter command: ")
    tn.write(command + "\r\n")
    ret1 = tn.read_eager()
    print(ret1)
    

    I will point out these 3 things: 1. the encode function returns the encoded version of the string, it does't alter the string itself, so if you wish to change the command variable, you should use command = command.encode("utf-8"). 2. I used \r\n, since this is a Windows machine. 3. Also, I am not sure if this is what you meant to do, but your join was inserting a \n between every single character in your command string.

    EDIT 24.07.15 Since you are using Python 3, I downloaded Python 3 and gave it another go. Here's a code that worked for me:

    HOST = input("IP Address: ")
    tn = telnetlib.Telnet(HOST, port = 23, timeout = 20)
    time.sleep(10)
    command = input("Enter command: ") + "\r\n"
    tn.write(command.encode('utf-8'))
    ret1 = tn.read_eager()
    print(ret1)
    

    The reason you received this error, is because you didn't receive encode's return value back into the command variable, so it stayed unaltered. Therefore, when you called write with command, it still received a string, which it was not expecting. 2 side notes - you need to use "\r\n", not just "\n", assuming you're using a Windows telnet server, though "\n" is fine with UNIX systems; I don't know the configuration of your telnet server, but, by default, they require authentication, so there's a chance you will have to enter credentials before entering a command.