librelist archives

« back to archive

the stdout was null?

the stdout was null?

From:
张俊峰
Date:
2015-07-08 @ 16:07
i was write a scriept like this, but i get the stdout  that was null?
how to fix it?

#!/usr/bin/python2
#coding:utf8

import commands
import os
import sys
import errno
import socket
import subprocess
import paramiko
import fcntl
import time
import threading
import struct
import urllib2
import re
import signal
import json
from paramiko import SSHException

class Exp(Exception):
    def __init__(self, errno, err, out = None):
        self.errno = errno
        self.err = err
        self.out = out

    def __str__(self):
        exp_info = 'errno:%s, err:%s'%(self.errno, self.err)
        if self.out is not None:
            exp_info += ' stdout:' + self.out
        return repr(exp_info)


def _exec_remote2(host, cmd, user = "root", password=None, timeout = 1):
    stdout = ""
    stderr = ""
    status = 0

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host, 22, user, password, timeout = timeout)
    transport = client.get_transport()
    session = transport.open_channel(kind='session')

    try:
        session.exec_command(cmd)
        while True:
            if session.recv_ready():
                data = session.recv(4096)
                stdout = stdout + data

            if session.recv_stderr_ready():
                data = session.recv_stderr(4096)
                stderr = stderr + data

            if session.exit_status_ready():
                if session.recv_ready():
                    data = session.recv(4096)
                    stdout = stdout + data

                if session.recv_stderr_ready():
                    data = session.recv_stderr(4096)
                    stderr = stderr + data

                break

        status = session.recv_exit_status()

    except socket.timeout as err:
        raise Exp(err.errno, 'Socket timeout')
    except socket.error as err:
        raise Exp(err.errno, err.strerror)
    except paramiko.AuthenticationException as err:
        raise Exp(250, 'Authentication failed')

    session.close()
    client.close()
    return stdout, stderr, status

if __name__ == '__main__':
    while True:
        stdout, stderr, status = _exec_remote2("192.168.120.63", 
"hostname", user = "root", password=None, timeout = 1)
        print stdout, stderr, status
        if not stdout.strip():
            print 'stdout is null'
            break