如何使用paramiko从远程命令执行获得完整的输出

时间:2014-02-15 16:03:08

标签: python paramiko

我正在尝试使用python paramiko代码学习在远程系统上执行命令。 我收到长度为12519个字符的部分输出。 如何获得12550或更长的完整结果?

以下是代码,这是从仅限互联网的其他网站获取的代码

def _run_poll(self, session, timeout, input_data):
    '''
    Poll until the command completes.

    @param session     The session.
    @param timeout     The timeout in seconds.
    @param input_data  The input data.
    @returns the output
    '''
    interval = 0.1
    maxseconds = timeout
    maxcount = maxseconds / interval

    # Poll until completion or timeout
    # Note that we cannot directly use the stdout file descriptor
    # because it stalls at 64K bytes (65536).
    input_idx = 0
    timeout_flag = False
    self.info('polling (%d, %d)' % (maxseconds, maxcount))
    start = datetime.datetime.now()
    start_secs = time.mktime(start.timetuple())
    output = ''
    session.setblocking(0)
    while True:
        if session.recv_ready():
            data = session.recv(self.bufsize)
            output += data
            self.info('read %d bytes, total %d' % (len(data), len(output)))
            print('[{}]'.format(output))
            #this prints partial output of 12519 characters

            if session.send_ready():
                # We received a potential prompt.
                # In the future this could be made to work more like
                # pexpect with pattern matching.
                if input_idx < len(input_data):
                    data = input_data[input_idx] + '\n'
                    input_idx += 1
                    self.info('sending input data %d' % (len(data)))
                    session.send(data)

        self.info('session.exit_status_ready() = %s' % (str(session.exit_status_ready())))
        if session.exit_status_ready():
            print('here') #this line is also printed
            break

        # Timeout check
        now = datetime.datetime.now()
        now_secs = time.mktime(now.timetuple())
        et_secs = now_secs - start_secs
        self.info('timeout check %d %d' % (et_secs, maxseconds))
        if et_secs > maxseconds:
            self.info('polling finished - timeout')
            timeout_flag = True
            break
        time.sleep(0.200)

    self.info('polling loop ended')
    if session.recv_ready():
        data = session.recv(self.bufsize)
        output += data
        self.info('read %d bytes, total %d' % (len(data), len(output)))

    self.info('polling finished - %d output bytes' % (len(output)))
    if timeout_flag:
        self.info('appending timeout message')
        output += '\nERROR: timeout after %d seconds\n' % (timeout)
        session.close()

    return output

0 个答案:

没有答案