Beispiel #1
0
 def __SendBinary(self, content):
     if self._socket is None:
         raise IxNetError('not connected')
     else:
         try:
             self._socket.sendall(content)
         except (socket.error, ):
             e = sys.exc_info()[1]
             self.__Close()
             raise IxNetError('Error:' + str(e))
Beispiel #2
0
 def __Send(self, content):
     if self._socket is None:
         raise IxNetError('not connected')
     else:
         try:
             if type(content) is str:
                 content = content.encode('ascii')
             self._socket.sendall(content)
         except (socket.error, ):
             e = sys.exc_info()[1]
             self.__Close()
             raise IxNetError('Error:' + str(e))
Beispiel #3
0
 def setSessionParameter(self, *args):
     if len(args) % 2 == 0:
         return self.__SendRecv('ixNet', 'setSessionParameter', *args)
     else:
         raise IxNetError(
             'setSessionParameter requires an even number of name/value pairs'
         )
Beispiel #4
0
 def _isConnected(self, raiseError=False):
     if self._socket is None:
         if raiseError is True:
             raise IxNetError('not connected')
         else:
             return False
     else:
         return True
Beispiel #5
0
    def __initialConnect(self, address, port, options):
        # make an initial socket connection
        # this will keep trying as it could be connecting to the proxy
        # which may not have an available application instance at that time
        attempts = 0
        while True:
            try:
                self._socket = socket.socket(socket.AF_INET,
                                             socket.SOCK_STREAM)
                self._socket.connect((address, port))
                break
            except (socket.error, ):
                if self._proxySocket is not None and attempts < 120:
                    time.sleep(2)
                    attempts += 1
                else:
                    self.__Close()
                    raise IxNetError(str(sys.exc_info()[1]))

        # a socket connection has been made now read the type of connection
        # setup to timeout if the remote endpoint is not valid
        self._socket.setblocking(0)
        read, write, error = select.select([self._socket], [], [], 30)
        if len(read) == 0 and len(write) == 0 and len(error) == 0:
            self.__Close()
            raise IxNetError('Connection handshake timed out after 30 seconds')
        self._socket.setblocking(1)

        # process the results from the endpoint
        try:
            connectString = self.__Recv()
            if connectString == 'proxy':
                self._socket.sendall(options.encode('ascii'))
                self._connectTokens = str(self.__Recv())
                connectTokens = dict(
                    list(
                        zip(self._connectTokens.split()[::2],
                            self._connectTokens.split()[1::2])))
                self._proxySocket = self._socket
                self._socket = None
                self.__initialConnect(address, int(connectTokens['-port']), '')
        except:
            self.__Close()
            raise
Beispiel #6
0
    def __SendRecv(self, *args):
        if self._socket is None:
            raise IxNetError('not connected')

        self._addContentSeparator = 0
        self._firstItem = True

        argList = list(args)

        if self._async:
            argList.insert(1, '-async')

        if self._timeout is not None:
            argList.insert(1, '-timeout')
            argList.insert(2, self._timeout)

        for item in argList:
            self.__Join(item)

        self._sendContent.append('\03')
        self._sendBuffer.append(''.join(self._sendContent))
        if self._buffer is False:
            buffer = ''.join(self._sendBuffer)
            self._log('Sending: {0}'.format(buffer))
            self.__Send('<001><002><009{0}>{1}'.format(len(buffer), buffer))
            self._sendBuffer = list()

        self._async = False
        self._timeout = None
        self._buffer = False
        self._sendContent = list()

        if len(self._sendBuffer) > 0:
            return self._OK
        else:
            return self.__Recv()
Beispiel #7
0
    def __Recv(self):
        self._decoratedResult = list()
        responseBuffer = str()
        try:
            while True:
                responseBuffer = str()
                commandId = None
                contentLength = int(0)

                while True:
                    responseBuffer += self._socket.recv(1).decode('ascii')
                    startIndex = int(responseBuffer.find('<'))
                    stopIndex = int(responseBuffer.find('>'))
                    if startIndex != -1 and stopIndex != -1:
                        commandId = int(responseBuffer[startIndex +
                                                       1:startIndex + 4])
                        if startIndex + 4 < stopIndex:
                            contentLength = int(responseBuffer[startIndex +
                                                               4:stopIndex])
                        break

                if commandId == 1:
                    self._evalResult = self._evalError
                    self._socket.recv(contentLength)
                elif commandId == 3:
                    self._socket.recv(contentLength)
                elif commandId == 4:
                    self._evalResult = self._socket.recv(contentLength).decode(
                        'ascii')
                elif commandId == 7:
                    self._filename = self._socket.recv(contentLength).decode(
                        'ascii')
                elif commandId == 8:
                    binaryFile = None
                    try:
                        binaryFile = io.open(self._filename, 'w+b')
                        chunk = bytearray()
                        bytesToRead = 32767
                        while contentLength > 0:
                            if contentLength < bytesToRead:
                                bytesToRead = contentLength
                            chunk = self._socket.recv(bytesToRead)
                            binaryFile.write(chunk)
                            contentLength -= len(chunk)
                    finally:
                        if binaryFile is not None:
                            binaryFile.close()
                elif commandId == 9:
                    self._decoratedResult = list()
                    chunk = str()
                    bytesToRead = 32767
                    while contentLength > 0:
                        if contentLength < bytesToRead:
                            bytesToRead = contentLength
                        chunk = self._socket.recv(bytesToRead).decode('ascii')
                        self._decoratedResult.append(chunk)
                        contentLength -= len(chunk)
                    break

        except (socket.error, ):
            e = sys.exc_info()[1]
            self.__Close()
            raise IxNetError('Recv failed. Error:' + str(e))

        self._log('Received: {0}'.format(''.join(self._decoratedResult)))

        if self._evalResult == self._evalError:
            raise IxNetError(''.join(self._decoratedResult))

        if len(self._decoratedResult
               ) > 0 and self._decoratedResult[0].startswith('\01'):
            self._decoratedResult[0] = self._decoratedResult[0].replace(
                '\01', '')
            return eval(''.join(self._decoratedResult))
        else:
            return ''.join(self._decoratedResult)
Beispiel #8
0
 def __CheckObjRef(self, objRef):
     if (type(objRef) in (str, unicode)) is False:
         raise IxNetError('The objRef parameter must be ' + str(str) +
                          ' instead of ' + str(type(objRef)))
     else:
         return objRef
Beispiel #9
0
    def connect(self, address, *args):
        try:
            if self._socket is not None:
                self.__SendRecv('ixNet', 'help')
        except:
            self.__Close()

        try:
            nameValuePairs = {}
            name = None
            serverusername = None
            sessionId = None
            for arg in args:
                if str(arg).startswith('-'):
                    if name is None:
                        name = str(arg)
                    else:
                        nameValuePairs[name] = ''
                elif name is not None:
                    nameValuePairs[name] = str(arg)
                    name = None
            if '-port' not in nameValuePairs:
                nameValuePairs['-port'] = 8009
            port = int(nameValuePairs['-port'])

            options = '-clientusername ' + getpass.getuser()
            if '-serverusername' in nameValuePairs:
                options += ' -serverusername ' + nameValuePairs[
                    '-serverusername']
                serverusername = nameValuePairs['-serverusername']
            if '-connectTimeout' in nameValuePairs:
                options += ' -connectTimeout ' + nameValuePairs[
                    '-connectTimeout']
            if '-closeServerOnDisconnect' in nameValuePairs:
                options += ' -closeServerOnDisconnect ' + nameValuePairs[
                    '-closeServerOnDisconnect']
            else:
                options += ' -closeServerOnDisconnect true'
            if '-sessionId' in nameValuePairs:
                options += ' -sessionId ' + nameValuePairs['-sessionId']
                sessionId = nameValuePairs['-sessionId']

            if self._socket is None:
                self.__initialConnect(address, port, options)
                conRes = self.__SendRecv('ixNet', 'connect', address,
                                         '-clientType', 'python', *args)
                self._CheckClientVersion()
                self._port = port
                self._address = address
                self._sessionId = self.getSessionId()
                self._serverusername = serverusername
                return conRes
            else:
                if (address != self._address or port != self._port):
                    return 'Cannot connect to {0}:{1} as a connection is already established to {2}:{3}. Please execute disconnect before trying this command again.'.format(
                        address, port, self._address, self._port)
                elif sessionId and sessionId != self._sessionId:
                    return 'Cannot connect to session {newId} as a connection is already established to session {currentId}. Please execute disconnect before trying this command again.'.format(
                        newId=sessionId, currentId=self._sessionId)
                elif serverusername and serverusername != self._serverusername:
                    return 'Cannot connect to a session associated with {newUsername} as a connection is already established to a session associated with {currentUsername}. Please execute disconnect before trying this command again.'.format(
                        newUsername=serverusername,
                        currentUsername=self._serverusername)
                else:
                    return self._OK
        except:
            e = sys.exc_info()[1]
            self.__Close()
            raise IxNetError(
                'Unable to connect to %s:%s. Error: %s' %
                (str(address), str(nameValuePairs['-port']), str(e)))