I want to use pexpect on Windows to open a telnet connection and to be able to read the "welcome message" (i.e. the output you get when you connect to some device). This is working with telnetlib3 using the following code
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())
but this unfortunately uses asynchronous methods and hence is very cumbersome to use.
To avoid these issues I want to use pexpect to do the same, but with the following code I am not able to get that "welcome message" as for telnetlib3:
import time
from pexpect import popen_spawn
session = popen_spawn.PopenSpawn("telnet 192.168.200.10 9000")
time.sleep(5)
data = session.read_nonblocking(4096, 1)
print(data)
In that case, I do not get any output. Is there something I am missing? How to get the "welcome message" using pexpect on Windows?
Running the command
telnet 192.168.200.10 9000
in a Windows terminal works as expected, i.e. I get this "welcome message".
The problem seems to be part of the "telnet" "negotiation" when the server sends commands like "IAC" and "DO", which I do not read on the client side (see HERE). But why does this work for telnetlib3 but not for telnetlib? What is the difference?



This might do what you want:
Running this against telehack (on my linux system; I am assuming that Windows telnet will behave similarly) produces:
This code works by:
pyexpect.EOF)timeoutparameter on theexpectmethod to time out if we don't receive it in 2 secondsbeforeattribute (text received before the expected string) to get the information we want