Example #1
0
    def receive(self, command=None, prompts=None, answer=None):
        '''
        Handles receiving of output from command
        '''
        recv = BytesIO()
        handled = False

        self._matched_prompt = None

        while True:
            data = self._ssh_shell.recv(256)

            # when a channel stream is closed, received data will be empty
            if not data:
                break

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())
            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                return self._sanitize(resp, command)
Example #2
0
    def create_package(self):
        data = BytesIO()

        with zipfile.ZipFile(data, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            for root, _dummy, filenames in os.walk(self.src):
                for filename in filenames:
                    src_path = os.path.join(root, filename)
                    dst_path = os.path.relpath(src_path, self.src)

                    if self.include:
                        if not any(fnmatch.fnmatch(src_path, pattern) for pattern in self.include):
                            continue

                    if self.exclude:
                        if any(fnmatch.fnmatch(src_path, pattern) for pattern in self.exclude):
                            continue

                    dst_path = self.rename.get(dst_path, dst_path)

                    zip_info = zipfile.ZipInfo(
                        dst_path,
                        (1980, 1, 1, 0, 0, 0),  # deterministic timestamp for idempotency
                    )

                    zip_info.compress_type = zipfile.ZIP_DEFLATED
                    zip_info.external_attr = 0o777 << 16  # give full access to included file

                    with open(src_path, 'rb') as src_file:
                        zip_file.writestr(zip_info, src_file.read())

        return data.getvalue()
Example #3
0
    def receive(self, command=None, prompts=None, answer=None, newline=True):
        '''
        Handles receiving of output from command
        '''
        recv = BytesIO()
        handled = False

        self._matched_prompt = None

        while True:
            data = self._ssh_shell.recv(256)

            # when a channel stream is closed, received data will be empty
            if not data:
                break

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())
            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer, newline)
            elif prompts and handled:
                # check again even when handled, a sub-prompt could be
                # repeating (like in the case of a wrong enable password, etc)
                self._handle_prompt(window, prompts, answer, newline)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                return self._sanitize(resp, command)
Example #4
0
    def receive(self, cmd=None):
        recv = BytesIO()
        handled = False

        while True:
            data = self.shell.recv(200)

            recv.write(data)
            recv.seek(recv.tell() - len(data))

            window = self.strip(recv.read().decode('utf8'))

            if cmd:
                if 'prompt' in cmd and not handled:
                    handled = self.handle_prompt(window, cmd)

            try:
                if self.find_prompt(window):
                    resp = self.strip(recv.getvalue().decode('utf8'))
                    if cmd:
                        resp = self.sanitize(cmd, resp)
                    return resp
            except ShellError:
                exc = get_exception()
                exc.command = cmd['command']
                raise
    def create_package(self, code):
        data = BytesIO()
        zip_info = zipfile.ZipInfo(
            'lambda_function.py',
            (1980, 1, 1, 0, 0, 0),
        )
        zip_info.compress_type = zipfile.ZIP_DEFLATED
        zip_info.external_attr = 0o777 << 16  # give full access to included file

        with zipfile.ZipFile(data, 'w', zipfile.ZIP_DEFLATED) as f:
            f.writestr(zip_info, code)

        return data.getvalue()
Example #6
0
    def receive(self,
                command=None,
                prompts=None,
                answer=None,
                newline=True,
                prompt_retry_check=False,
                check_all=False):
        '''
        Handles receiving of output from command
        '''
        recv = BytesIO()
        handled = False

        self._matched_prompt = None
        self._matched_cmd_prompt = None
        matched_prompt_window = window_count = 0

        while True:
            data = self._ssh_shell.recv(256)

            # when a channel stream is closed, received data will be empty
            if not data:
                break

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())
            window_count += 1

            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer, newline,
                                              False, check_all)
                matched_prompt_window = window_count
            elif prompts and handled and prompt_retry_check and matched_prompt_window + 1 == window_count:
                # check again even when handled, if same prompt repeats in next window
                # (like in the case of a wrong enable password, etc) indicates
                # value of answer is wrong, report this as error.
                if self._handle_prompt(window, prompts, answer, newline,
                                       prompt_retry_check, check_all):
                    raise AnsibleConnectionFailure(
                        "For matched prompt '%s', answer is not valid" %
                        self._matched_cmd_prompt)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                return self._sanitize(resp, command)
Example #7
0
def connection_response(name, path, status=200):
    file = os.path.join(path, name)
    with open(file, 'rb') as f:
        response_data = BytesIO(f.read())
    response_mock = Mock()
    response_mock.getcode.return_value = status
    return response_mock, response_data
 def _send_response(status_code, response):
     response_mock = mock.Mock()
     response_mock.getcode.return_value = status_code
     response_text = response
     response_data = BytesIO(
         response_text.encode() if response_text else "".encode())
     return response_mock, response_data
Example #9
0
 def _connection_response(response, status=200):
     response_mock = mock.Mock()
     response_mock.getcode.return_value = status
     response_text = json.dumps(
         response) if type(response) is dict else response
     response_data = BytesIO(
         response_text.encode() if response_text else ''.encode())
     return response_mock, response_data
 def _download_extract_zip(self, url):
     from ansible.module_utils.urls import open_url
     from ansible.module_utils.six import BytesIO
     from zipfile import ZipFile
     if not os.path.isdir(self.directory):
         os.makedirs(self.directory)
     resp = open_url(url)
     zip_archive = ZipFile(BytesIO(resp.read()))
     zip_archive.extractall(path=self.terraform_dir)
Example #11
0
    def send(self, path, data, **kwargs):
        '''
        Sends the command to the device over api
        '''
        url_kwargs = dict(
            timeout=self.get_option('timeout'),
            validate_certs=self.get_option('validate_certs'),
            headers={},
        )
        url_kwargs.update(kwargs)
        if self._auth:
            # Avoid modifying passed-in headers
            headers = dict(kwargs.get('headers', {}))
            headers.update(self._auth)
            url_kwargs['headers'] = headers
        else:
            url_kwargs['url_username'] = self.get_option('remote_user')
            url_kwargs['url_password'] = self.get_option('password')

        try:
            response = open_url(self._url + path, data=data, **url_kwargs)
        except HTTPError as exc:
            is_handled = self.handle_httperror(exc)
            if is_handled is True:
                return self.send(path, data, **kwargs)
            elif is_handled is False:
                raise AnsibleConnectionFailure(
                    'Could not connect to {0}: {1}'.format(
                        self._url + path, exc.reason))
            else:
                raise
        except URLError as exc:
            raise AnsibleConnectionFailure(
                'Could not connect to {0}: {1}'.format(self._url + path,
                                                       exc.reason))

        response_buffer = BytesIO()
        response_buffer.write(response.read())

        # Try to assign a new auth token if one is given
        self._auth = self.update_auth(response, response_buffer) or self._auth

        return response, response_buffer
Example #12
0
def connection_response(response, status=200, headers=None):
    response_mock = Mock()
    response_mock.getcode.return_value = status
    if headers is None:
        headers = BASE_HEADERS
    response_mock.getheaders.return_value = headers.items()
    response_text = json.dumps(
        response) if type(response) is dict else response
    response_data = BytesIO(
        response_text.encode() if response_text else ''.encode())
    return response_mock, response_data
Example #13
0
def download_response(file, status=200):
    response_mock = MagicMock()
    bytes_file = bytes(file, encoding='utf8')
    response_mock_buffer = BytesIO(bytes_file)
    response_mock.status = status
    content_range = '0-{0}/{1}'.format(str(len(bytes_file)),
                                       str(len(bytes_file)))
    response_mock.headers = {
        'Content-Range': content_range,
        'Content-Type': 'application/octet-stream'
    }

    return response_mock, response_mock_buffer
Example #14
0
    def receive(self, command=None, prompts=None, answer=None):
        """Handles receiving of output from command"""
        recv = BytesIO()
        handled = False

        self._matched_prompt = None

        while True:
            data = self._shell.recv(256)

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())

            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                return self._sanitize(resp, command)
Example #15
0
    def receive(self, command=None, prompts=None, answer=None, newline=True, prompt_retry_check=False):
        '''
        Handles receiving of output from command
        '''
        recv = BytesIO()
        handled = False

        self._matched_prompt = None
        self._matched_cmd_prompt = None
        matched_prompt_window = window_count = 0

        while True:
            data = self._ssh_shell.recv(256)

            # when a channel stream is closed, received data will be empty
            if not data:
                break

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())
            window_count += 1

            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer, newline)
                matched_prompt_window = window_count
            elif prompts and handled and prompt_retry_check and matched_prompt_window + 1 == window_count:
                # check again even when handled, if same prompt repeats in next window
                # (like in the case of a wrong enable password, etc) indicates
                # value of answer is wrong, report this as error.
                if self._handle_prompt(window, prompts, answer, newline, prompt_retry_check):
                    raise AnsibleConnectionFailure("For matched prompt '%s', answer is not valid" % self._matched_cmd_prompt)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                return self._sanitize(resp, command)
Example #16
0
    def receive(self, command=None, prompts=None, answer=None):
        """Handles receiving of output from command"""
        recv = BytesIO()
        handled = False

        self._matched_prompt = None

        while True:
            data = self._shell.recv(256)

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())

            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                return self._sanitize(resp, command)
Example #17
0
    def receive(self,
                command=None,
                prompts=None,
                answer=None,
                newline=True,
                prompt_retry_check=False,
                check_all=False):
        '''
        Handles receiving of output from command
        '''
        self._matched_prompt = None
        self._matched_cmd_prompt = None
        recv = BytesIO()
        handled = False
        command_prompt_matched = False
        matched_prompt_window = window_count = 0

        command_timeout = self.get_option('persistent_command_timeout')
        self._validate_timeout_value(command_timeout,
                                     "persistent_command_timeout")

        buffer_read_timeout = self.get_option('persistent_buffer_read_timeout')
        self._validate_timeout_value(buffer_read_timeout,
                                     "persistent_buffer_read_timeout")

        while True:
            if command_prompt_matched:
                try:
                    signal.signal(signal.SIGALRM,
                                  self._handle_buffer_read_timeout)
                    signal.setitimer(signal.ITIMER_REAL, buffer_read_timeout)
                    data = self._ssh_shell.recv(256)
                    signal.alarm(0)
                    # if data is still received on channel it indicates the prompt string
                    # is wrongly matched in between response chunks, continue to read
                    # remaining response.
                    command_prompt_matched = False

                    # restart command_timeout timer
                    signal.signal(signal.SIGALRM, self._handle_command_timeout)
                    signal.alarm(command_timeout)

                except AnsibleCmdRespRecv:
                    return self._command_response
            else:
                data = self._ssh_shell.recv(256)

            # when a channel stream is closed, received data will be empty
            if not data:
                break

            recv.write(data)
            offset = recv.tell() - 256 if recv.tell() > 256 else 0
            recv.seek(offset)

            window = self._strip(recv.read())
            window_count += 1

            if prompts and not handled:
                handled = self._handle_prompt(window, prompts, answer, newline,
                                              False, check_all)
                matched_prompt_window = window_count
            elif prompts and handled and prompt_retry_check and matched_prompt_window + 1 == window_count:
                # check again even when handled, if same prompt repeats in next window
                # (like in the case of a wrong enable password, etc) indicates
                # value of answer is wrong, report this as error.
                if self._handle_prompt(window, prompts, answer, newline,
                                       prompt_retry_check, check_all):
                    raise AnsibleConnectionFailure(
                        "For matched prompt '%s', answer is not valid" %
                        self._matched_cmd_prompt)

            if self._find_prompt(window):
                self._last_response = recv.getvalue()
                resp = self._strip(self._last_response)
                self._command_response = self._sanitize(resp, command)
                if buffer_read_timeout == 0.0:
                    return self._command_response
                else:
                    command_prompt_matched = True