使用Python的telnetlib进行非常慢的交互

pc3*_*c3e 5 python telnet

我正在编写一个Python脚本,该脚本通过Telnet连接到Linux终端,运行许多命令并解析输出,然后根据输出运行更多命令,等等。

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?

小智 1

我遇到了与您相同的问题,我正在执行“read_until”,它在一台机器上运行速度非常慢,而在另一台机器上运行速度很快...我将代码切换为“read_very_eager”并在请求之间设置了小暂停,如下例所示。现在我的代码在任何地方都以相同的速度运行。如果您错过了一些响应,请尝试使变量“wait”=更大。

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
Run Code Online (Sandbox Code Playgroud)