Paramiko输出不一致?

时间:2016-04-28 04:40:12

标签: python python-3.x

帕拉米科每次跑步给我不同的输出,只是好奇为什么会这样。有时它会返回:

The programs included with the Debian GNU/Linux system are free software;
...

$ 
$ su -
Password: 

有时它会返回:

The programs included with the Debian GNU/Linux system are free software;
...

$ $ su -
Password: 

这是我的代码:

def execute_shell_command(self, command, timeout=10, wait_for_answer=True):
    if self.session is None:
        message = "'{}' could not execute '{}', session is not open".format(self.interface_id, command)
        self.sys_conf.logger.warning(message)
        raise SessionIsNotAvailable(message)

    channel = self.shell
    channel.set_combine_stderr(True)
    output_lines = []
    try:
        # Clear the buffer before executing any commands
        while channel.recv_ready():
            output_lines.append(channel.recv(99999).decode("utf-8", "ignore"))

        # Execute command, wait {timeout} seconds and try to clear the buffer again.
        channel.send('{}\n'.format(command))
        time.sleep(timeout)
        if wait_for_answer:
            while channel.recv_ready():
                output_lines.append(channel.recv(99999).decode("utf-8", "ignore"))

    except socket.timeout as e:
        message = "Timeout reached - failed to execute command '{}'".format(command)
        self.sys_conf.logger.warning(message)
        raise ExecutionTimeout(message, e)

    answer = "".join(output_lines)
    if wait_for_answer:
        return answer

对我来说似乎很奇怪,因为它与同一台服务器的命令相同,所以不应该有任何区别。

1 个答案:

答案 0 :(得分:0)

我认为这是因为:

channel.set_combine_stderr(True)

你告诉Paramiko将stdout和stderr合并为一个流。但是如何做到这一点可能取决于时机。

您可能会尝试不组合流,然后看看会发生什么。