KeyboardInterrupt处理非常慢。问题出在哪里?

时间:2019-01-16 13:54:28

标签: paramiko keyboardinterrupt

我目前正在尝试编写脚本以通过paramiko读取shell,到目前为止,如果我提示一个命令,它会很好用。

问题是我的实际目标是处理调试流,并且我当然不能使用超时,因为脚本应该不受时间限制地进行监听。

因此,另一种选择是让用户使用 ctrl - c 停止流。我添加了一个“尝试,除外”处理程序,例如

except (IOError, SystemExit):
    raise
except KeyboardInterrupt:
    print ("Crtl+C Pressed. Shutting down.")

似乎不起作用:按ctrl-c时没有任何反应。但是后来我意识到这将永远耗光:几分钟后,脚本实际上停止了,并且出现了消息。

有人知道如何处理此问题吗?

仅供参考,这是我的代码

import paramiko
import time
import re
import socket
import os

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

address = '192.168.1.1'
username = 'admin' 
password = ''

ssh.connect(address, port=22, username = username, password = password)

shell = ssh.invoke_shell(height=400)
shell.settimeout(2)

def prompt_console(command = '', channel = shell, timeout = False):
    print(channel.recv(9999).decode('utf-8'))           #<-- this is for removing the initial prompt from buffer
    if timeout == False:
        shell.settimeout(3600)                          #<--increasing the timeout
    channel.send(command+'\n')
    log = ''
    while True:
        try:
            log += channel.recv(1).decode('utf-8')      #<--every loop it loads a char into the "log" variable
            if log[-9:] == '--More-- ':
                shell.send(" ")
                log.replace('--More-- \r         \r\t\t','\r\t\t')
            if len(re.findall('.*\n',log))>0:           #<--it yields every line to python console
                yield log
                log = ''
        except (IOError, SystemExit):
            raise
        except KeyboardInterrupt:
            print ("Crtl+C Pressed. Shutting down.")

我也试图将try-except放在while循环之外,但是没有用。我还尝试了很多在google上发现的建议,但它们也都没有用:它们最终都停止了脚本,但是所有这些都需要5到10分钟。

0 个答案:

没有答案
相关问题