I have a python code with telnetlib3
as follows:
import asyncio
import telnetlib3
async def foo():
reader, writer = await telnetlib3.open_connection("192.168.200.10", 9000)
data = await asyncio.wait_for(reader.read(4096), timeout=2)
print(data)
asyncio.run(foo())
that is able to connect to a telnet service and returns the following expected output on a Linux and Windows system:
Terminal emulator detected (unknown), switching to interactive shell
Debug server connected. Waiting for commands (or 'exit')...
Supported client terminals: telnet, screen, PuTTY.
prompt >>
However, when I use telnetlib
as in the following example:
import time
import telnetlib
session = telnetlib.Telnet("192.168.200.10", 9000, 2)
received = b""
t0 = time.time()
while time.time() - t0 < 2:
data = session.read_very_eager()
if data:
received += data
t0 = time.time()
print(received)
the output is something like
b'x1b[0Gx1b[0G'
on Linux and windows.
How can I modify the first code example (using telnetlib
) so I receive the "interactive welcome message" as I do with telnetlib3
on Windows?
- windows: windows10, python 3.10.11
- linux (VM on windows): Ubuntu 20.04.6, python 3.8.10
2
Answers
Note that
telnetlib
is deprecated since Python version 3.11, and will be removed in version 3.13.Your Python version is OK, but… don’t upgrade it too quickly!
telnetlib
is a bit lower-level thantelnetlib3
: it does not automatically handle some of the telnet protocol interactions thattelnetlib3
does for you. The binary output you are seeing is likely part of the Telnet protocol negotiation thattelnetlib3
is handling automatically, buttelnetlib
is not.You can try and mirror the functionality of your
telnetlib3
version by manually handling the Telnet protocol negotiation, withtelnetlib.Telnet.set_option_negotiation_callback
. It does not handle all cases – it is only designed to work with your specific server.Inspired from "
robot.libraries.Telnet
", but… very much simplified.See also "Python
telnetlib.WILL
Examples "The
handle_option
function is a callback thattelnetlib
will use to respond to Telnet option commands from the server. It essentially it is telling the server that we will handle terminal type (TTYPE
) options and that we will not handle any other options.That code should give you similar results to your
telnetlib3
version, but it is a bit more complex becausetelnetlib
requires you to handle more of the protocol details manually.Also, I have used
decode()
method (as in this example) at the end to convert binary data into string. Do remove it if your data is not text.