Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very slow interaction using Python's telnetlib

Tags:

python

telnet

I'm writing a Python script that connects to a Linux terminal over Telnet, runs a number of commands and parses the output, then based on the output runs more commands, etc.

This was quite easy to set up using telnetlib. I'm using write(cmd + '\n') to send the command and then read_until(prompt) to read the output. The problem I'm having is that this setup seems to be very slow. Every command takes maybe around 100-200 ms to run. This makes the total run time around half a minute, which I find to be too long.

If I connect to the terminal using a normal Telnet client the commands I'm trying to run return near instantly. I've also made a small bash script that runs ~20 commands that also returns near instantly. Also I tried some of the other read functions in telnetlib (such as read_very_eager()) without any improvement.

Does anyone know why this setup is so slow and if there's anything I can do about it?

like image 771
pc3e Avatar asked Oct 29 '12 12:10

pc3e


1 Answers

I had the same problem you had, i was doing "read_until" and it was working very slow on one machine and fast on the other... I switched my code to "read_very_eager" and put small pauses between request like in example bellow. Now my code works with the same speed everywhere. If you missing some of the responses try to make variable "wait" = bigger.

tn = telnetlib.Telnet(host)
wait=0.1

sleep(wait)              # wait for greeter
tn.read_very_eager();    # optional step
tn.write(PASSWORD+"\n")  # send password
sleep(wait)              # wait for prompt
tn.read_very_eager()     # optional step

tn.write("write some ting\n") # send your request
sleep(wait)                # wait for response to become available
print tn.read_very_eager() # read response IF you need it otherwise skip it
tn.write("write some thing else\n") # send your request
sleep(wait)                # wait for response to become available
print tn.read_very_eager() # read response IF you need it otherwise skip it
tn.write("exit\n")         # optional step
tn.close()                 # close connection
like image 57
Josh C Josh C Avatar answered Nov 17 '22 22:11

Josh C Josh C