Search code examples
pythontelnetlib

How to read telnet sessions with python


Aloha, i'm creating a teamspeakbot and want to write and read to a telnet session created with a TeamSpeak3 server

import telnetlib
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.read_all()

What i'm expecting:

Connected to localhost
Escape character is '^]'.
TS3
Welcome to the TeamSpeak 3 ServerQuery interface, type "help" for a li...

But instead i get a time out after the 10 seconds:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/telnetlib.py", line 325, in read_all
    self.fill_rawq()
  File "/usr/lib/python2.7/telnetlib.py", line 516, in fill_rawq
    buf = self.sock.recv(50)
socket.timeout: timed out

How can i read all stuff the telnet connection tells me and later write some stuff to it (like the login proces and submit commands and get the response ...)

The Solution is

tn.read_very_eager()

My code now looks like this:

import telnetlib, time
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.write('help\n')
time.sleep(0.05)
print(tn.read_very_eager())

Solution

  • read_all() blocks until EOF is reached*, or until your timeout is reached. While I've not used telnetlib much, I have assumed it's for the sort of service which displays something then closes the connection.

    How do you get on with code like:

    tn = telnetlib.Telnet('localhost', 10011, 10)
    tn.read_some()
    

    *https://docs.python.org/2/library/telnetlib.html#telnetlib.Telnet.read_all