[paramiko] recv的時候老是出現timeout的錯誤

# cat LIBS/COM_TSHARK/com_tshark.py
import os,sys,time,re
import socket,paramiko
from robot.api import loggershell

debug = Trueapi

try:
    lib_path =  os.environ['ROBOTREPO'] +'/LIBS/COM_TSHARK'
    if lib_path not in sys.path:
        sys.path.append(lib_path)
    
except Exception:
    raise AssertionError("Module: %s -> Fail to set sys.path" % __name__)
    
""" 
    To login the tshark server and launch the tshark 
    
    Its done with the help of paramiko module using ssh protocolsession

Author:  
qihz    Developed        
"""
class com_tshark(object) :
    """ 
    com_tshark is the class will have ip, port, username, password and exec_file arguments.
        
    Author:  
    Mahalakshmi Venkatraman     Developed        
    """
    def __init__(self,ip='127.0.0.1',port='22',username='atxuser',\
    password='alcatel01',prompt=".*\$|.*#|.*%") :
        self.ip = ip.encode("ascii")
        self.port = int(port.encode("ascii"))
        self.username = username.encode("ascii")
        self.password = password.encode("ascii")
        if prompt :
            self.prompt = prompt.encode("ascii")
        #transport and channel are the object variables which will have the transport & channel objects.
        self.transport = ""
        self.channel = ""
            
                         
    def open_tshark(self):
        """ 
        open_tshark will establish the ssh connection using paramiko and create a transport & channel objects for the
          ssh session & invoke the shell. Set the pty terminal session to run the sudo commands. Set default timeout
          as '3'. The channel will wait upto 3 seconds to get the data from the socket, else return.
            
        """
        keyword_name = "open_tshark"
        logger.debug("%s:%s " % (__name__,keyword_name))
        re_telnetTime = 0app

        while re_telnetTime < 10:
            try:                                
                self.transport = paramiko.Transport((self.ip, self.port))
                self.transport.connect(username = self.username, password = self.password)
                self.channel = self.transport.open_session()
                self.channel.settimeout(3)
                self.channel.get_pty('vt100')
                self.channel.invoke_shell()
                logger.debug("SSH session established successfully...")
            except Exception as inst:
                if re_telnetTime == 10:
                    raise AssertionError("%s:%s ->Can't open SSH TSHARK session, exception:%s" \
                    % (__name__,keyword_name,inst))
                try :
                    self.channel.close()
                    self.transport.close()
                except Exception as inst :                  
                    logger.debug("%s:%s : Closing channel and transport failed..." \
                % (__name__,keyword_name))
                re_telnetTime += 1
                logger.debug("%s:%s -> Try to SSH TSHARK the %d(th) time" \
                % (__name__,keyword_name,re_telnetTime))
                time.sleep(5)      
                continue         
            else:
                breakssh

        self.channel.settimeout(60)
        self.session_alive = True     
        return "pass"socket

    def reopen_tshark(self):
        iretry_count = 10
        i = 0
        while ( i <= iretry_count ) :
            i += 1
            msg = "try to reopen SSH Tshark for the %s(th) time" % str(i)
            logger.debug("%s:%s -> %s" % (__name__,'reopen_tshark',msg))
            try:
                self.open_tshark()
            except Exception as inst:
                pass
            if self.session_alive :
                return "pass"
            else :
                time.sleep(1)
                continuespa

        raise AssertionError("%s:%s ->Can't open TSHARK session, exception:%s" \
                    % (__name__,keyword_name,inst))
      
    def close_tshark(self):
        """ 
        close_tshark will close the ssh connection which is established using paramiko module
        """
        keyword_name = "close_tshark"
        resultFlag = "OK"
        self.channel.settimeout(3)
        try:
            expectPrompt = "\$|#|%"
            self.transport.close()
            self.channel.close()
        except Exception as inst:
            msg = "SSH Tshark can't been closed"
            raise AssertionError("%s:%s -> %s, exception: %s" \
            % (__name__,keyword_name,msg, inst))
             
        return "pass"         
    
    def send_command(self,tsharkCmd,prompt=".*\$|.*#|.*%"):
        keyword_name = "send_command".net

        i = 1
        while (i < 3) :
            i += 1
            logger.debug("SEND >> %s" % tsharkCmd)
            result = self._ssh_sendcmd(tsharkCmd,prompt)
            logger.debug("REPLY << %s" % result)debug

            if re.search(prompt,result) :
                return result
            else :
                logger.debug("not gotten prompt '%s'\n TSHARK response:" % (self.prompt,result))
        
        logger.debug("re-open tshark for next command sending")
        try :
            self.transport.close()
            self.channel.close()
            self.session_alive = False
            time.sleep(5)
            self.reopen_tshark()
        except Exception as inst :
            raise AssertionError("fail to reopen_tshark")
        else :
            raise AssertionError("fail to get prompt for tshark command:" +tsharkCmd) code


    def _exec_command(self,command,expectPrompt,message="execute command",timeout=5):
        keyword_name = "_exec_command"
        returnTmp = ""
        try:
            returnTmp = self._ssh_sendcmd(command+"\n")
            logger.debug("write:'%s', expect:'%s'" % (command,expectPrompt))
            logger.debug("get return:\n%s\n" % returnTmp)
        except Exception as inst:
            msg = "fail to " + message
            raise AssertionError("%s:%s-> %s,exception:%s" % (__name__,keyword_name,msg,inst))
        return returnTmp

  
    def _ssh_sendcmd(self,cmd,prompt=".*\$|.*#|.*%"):
        keyword_name = "_ssh_sendcmd"
        result = ""
        data = ""
        self.channel.send(cmd + '\n')
        # read the socket buffer until the channel exit_status_ready state
        while not self.channel.exit_status_ready():
            # read the socket buffer if the channel receive in ready state
            if self.channel.recv_ready() :
                # read the socket buffer
                data = self.channel.recv(1024)
                result = data
                while data :
                    try :
                        if re.search(prompt,result) :
                            return result
                        else :
                            data = self.channel.recv(1024)
                            logger.debug("recv data 2: %s" % data)
                            result += data
                            continue
                    except socket.timeout:
                        logger.debug("Receive Timeout Exception!")
                        return result
                    except Exception as inst :
                        logger.debug("Exception Error : %s" % (inst))
                        return result
            if self.channel.recv_stderr_ready():
                error_buf = self.channel.recv_stderr(1024)
                errinfo = ""
                while error_buf :
                    errinfo += error_buf
                    try :
                        error_buf = self.channel.recv_stderr(1024)
                    except Exception as inst :
                        logger.warning("Error : %s" % (inst))
                        return errinfo  
                                   
        return result
 

[root@localhost robot]# 

相關文章
相關標籤/搜索