首页 文章

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

提问于
浏览
4

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

这很容易使用telnetlib进行设置 . 我'm using write(cmd + ' \ n ') to send the command and then read_until(prompt) to read the output. The problem I'我知道这个设置似乎很慢 . 每个命令运行大约需要100-200毫秒 . 这使得总运行时间大约为半分钟,我发现它太长了 .

如果我使用普通的Telnet客户端连接到终端,我尝试运行的命令会立即返回 . 我还制作了一个小的bash脚本,运行~20个命令,它们也会立即返回 . 我还尝试了telnetlib中的一些其他读取函数(例如read_very_eager())而没有任何改进 .

有谁知道为什么这个设置太慢了,如果有什么我可以做的呢?

1 回答

  • 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
    

相关问题