paramiko ssh hanging in packet.py on windows machine

Viewed 54

I work on both Linux and Windows. As written here in many places, I am using the stdout.channel.eof_received workaround to avoid parmaiko's hanging on packet.py. My SSH code for Linux:

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]

It works great.

but... when I open SSH to Windows, this solution does not work. I never get to the EOF extension and I always go out of the loop to timeout... Does anyone have an idea for another workaround? I am currently running a python over ssh script and sometimes it's hanging when I try to read using readline() function.

My SSH code for windows:

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

thanks!

0 Answers
Related