首页 > 解决方案 > paramiko ssh 挂在 windows 机器上的 packet.py 中

问题描述

我在 Linux 和 Windows 上工作。正如在许多地方所写的那样,我正在使用 stdout.channel.eof_received 解决方法来避免 parmaiko 挂在 packet.py 上。我的 Linux SSH 代码:

def SendCommand(self, Command, GetOutput=False,timeout=20):
    log.info('SSH : ' + inspect.currentframe().f_code.co_name + '\nWith: ' + str(locals().items()))
    stdin, stdout, stderr = self.ssh.exec_command("echo '{}' | sudo -S {}".format(self.password, Command))
    resp = ''
    resperr = ''
    if GetOutput:
        endtime = time.time() + timeout
        while not stdout.channel.eof_received:
            time.sleep(0.5)
            if time.time() > endtime:
                stdout.channel.close()
                break
        outlines = stdout.readlines()
        outlinesstderr = stderr.readlines()
        resp = ''.join(outlines)
        resperr = ''.join(outlinesstderr)
    stdinstat, stdoutstat, stderrstat = self.ssh.exec_command('if [ $? -eq 0 ]; then echo OK; else echo FAIL; fi')
    outlines = stdoutstat.readlines()
    respstat = ''.join(outlines)
    log.info(f'SSHlog {Command} status:{respstat}')
    return [resp, resperr, respstat]

它工作得很好。

但是......当我打开 SSH 到Windows时,这个解决方案不起作用。我从来没有到达 EOF 扩展,而且我总是跳出循环超时......有没有人有另一种解决方法的想法?我目前正在通过 ssh 脚本运行 python,有时当我尝试使用 readline() 函数读取时它会挂起。

我的 Windows SSH 代码:

def send_windows_command_getResp(self, command):
    timeout = 1
    ssh_stdin, ssh_stdout, ssh_stderr = self.ssh.exec_command(command)
    endtime = time.time() + timeout
    while not ssh_stdout.channel.eof_received:
        time.sleep(0.5)
        if time.time() > endtime:
            ssh_stdout.channel.close()
            break
    response = ssh_stdout.readline().rstrip()
    return response

谢谢!

标签: pythonwindowssshparamiko

解决方案


推荐阅读