Ejemplo n.º 1
0
def ECSClient(entrust_api_user=None,
              entrust_api_key=None,
              entrust_api_cert=None,
              entrust_api_cert_key=None,
              entrust_api_specification_path=None):
    """Create an ECS client"""

    if not YAML_FOUND:
        raise SessionConfigurationException(missing_required_lib("PyYAML"),
                                            exception=YAML_IMP_ERR)

    if entrust_api_specification_path is None:
        entrust_api_specification_path = "https://cloud.entrust.net/EntrustCloud/documentation/cms-api-2.1.0.yaml"

    # Not functionally necessary with current uses of this module_util, but better to be explicit for future use cases
    entrust_api_user = to_text(entrust_api_user)
    entrust_api_key = to_text(entrust_api_key)
    entrust_api_cert_key = to_text(entrust_api_cert_key)
    entrust_api_specification_path = to_text(entrust_api_specification_path)

    return ECSSession(
        "ecs",
        entrust_api_user=entrust_api_user,
        entrust_api_key=entrust_api_key,
        entrust_api_cert=entrust_api_cert,
        entrust_api_cert_key=entrust_api_cert_key,
        entrust_api_specification_path=entrust_api_specification_path,
    ).client()
Ejemplo n.º 2
0
def get_laps_password(conn, cn, search_base):
    search_filter = u"(&(objectClass=computer)(CN=%s))" % to_text(cn)

    ldap_results = conn.search_s(to_text(search_base), ldap.SCOPE_SUBTREE, search_filter,
                                 attrlist=[u"distinguishedName", u"ms-Mcs-AdmPwd"])

    # Filter out non server hosts, search_s seems to return 3 extra entries
    # that are not computer classes, they do not have a distinguished name
    # set in the returned results
    valid_results = [attr for dn, attr in ldap_results if dn]

    if len(valid_results) == 0:
        raise AnsibleLookupError("Failed to find the server '%s' in the base '%s'" % (cn, search_base))
    elif len(valid_results) > 1:
        found_servers = [to_native(attr['distinguishedName'][0]) for attr in valid_results]
        raise AnsibleLookupError("Found too many results for the server '%s' in the base '%s'. Specify a more "
                                 "explicit search base for the server required. Found servers '%s'"
                                 % (cn, search_base, "', '".join(found_servers)))

    password = valid_results[0].get('ms-Mcs-AdmPwd', None)
    if not password:
        distinguished_name = to_native(valid_results[0]['distinguishedName'][0])
        raise AnsibleLookupError("The server '%s' did not have the LAPS attribute 'ms-Mcs-AdmPwd'" % distinguished_name)

    return to_native(password[0])
Ejemplo n.º 3
0
    def _get_hostname(self, instance, hostnames):
        '''
            :param instance: an instance dict returned by boto3 ec2 describe_instances()
            :param hostnames: a list of hostname destination variables in order of preference
            :return the preferred identifer for the host
        '''
        if not hostnames:
            hostnames = ['dns-name', 'private-dns-name']

        hostname = None
        for preference in hostnames:
            if 'tag' in preference:
                if not preference.startswith('tag:'):
                    raise AnsibleError(
                        "To name a host by tags name_value, use 'tag:name=value'."
                    )
                hostname = self._get_tag_hostname(preference, instance)
            else:
                hostname = self._get_boto_attr_chain(preference, instance)
            if hostname:
                break
        if hostname:
            if ':' in to_text(hostname):
                return self._sanitize_group_name((to_text(hostname)))
            else:
                return to_text(hostname)
Ejemplo n.º 4
0
    def get_device_info(self):
        device_info = {}

        device_info['network_os'] = 'nos'
        reply = self.get('show version')
        data = to_text(reply, errors='surrogate_or_strict').strip()

        match = re.search(r'Network Operating System Version: (\S+)', data)
        if match:
            device_info['network_os_version'] = match.group(1)

        reply = self.get('show chassis')
        data = to_text(reply, errors='surrogate_or_strict').strip()

        match = re.search(r'^Chassis Name:(\s+)(\S+)', data, re.M)
        if match:
            device_info['network_os_model'] = match.group(2)

        reply = self.get('show running-config | inc "switch-attributes host-name"')
        data = to_text(reply, errors='surrogate_or_strict').strip()

        match = re.search(r'switch-attributes host-name (\S+)', data, re.M)
        if match:
            device_info['network_os_hostname'] = match.group(1)

        return device_info
Ejemplo n.º 5
0
    def exec_command(self, cmd, in_data=None, sudoable=True):
        """ execute a command on the lxd host """
        super(Connection, self).exec_command(cmd,
                                             in_data=in_data,
                                             sudoable=sudoable)

        self._display.vvv(u"EXEC {0}".format(cmd), host=self._host)

        local_cmd = [
            self._lxc_cmd, "exec", self._host, "--",
            self._play_context.executable, "-c", cmd
        ]

        local_cmd = [
            to_bytes(i, errors='surrogate_or_strict') for i in local_cmd
        ]
        in_data = to_bytes(in_data,
                           errors='surrogate_or_strict',
                           nonstring='passthru')

        process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        stdout, stderr = process.communicate(in_data)

        stdout = to_text(stdout)
        stderr = to_text(stderr)

        if stderr == "error: Container is not running.\n":
            raise AnsibleConnectionFailure("container not running: %s" %
                                           self._host)

        if stderr == "error: not found\n":
            raise AnsibleConnectionFailure("container not found: %s" %
                                           self._host)

        return process.returncode, stdout, stderr
Ejemplo n.º 6
0
    def send_request(self, data, **message_kwargs):
        data = to_list(data)
        become = self._become
        if become:
            self.connection.queue_message('vvvv', 'firing event: on_become')
            data.insert(0, {"cmd": "enable", "input": self._become_pass})

        output = message_kwargs.get('output', 'text')
        request = request_builder(data, output)
        headers = {'Content-Type': 'application/json-rpc'}

        response, response_data = self.connection.send('/command-api',
                                                       request,
                                                       headers=headers,
                                                       method='POST')

        try:
            response_data = json.loads(to_text(response_data.getvalue()))
        except ValueError:
            raise ConnectionError(
                'Response was not valid JSON, got {0}'.format(
                    to_text(response_data.getvalue())))

        results = handle_response(response_data)

        if become:
            results = results[1:]
        if len(results) == 1:
            results = results[0]

        return results
Ejemplo n.º 7
0
    def _create_zip_tempfile(self, files, directories):
        tmpdir = tempfile.mkdtemp(dir=C.DEFAULT_LOCAL_TMP)
        zip_file_path = os.path.join(tmpdir, "win_copy.zip")
        zip_file = zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_STORED,
                                   True)

        # encoding the file/dir name with base64 so Windows can unzip a unicode
        # filename and get the right name, Windows doesn't handle unicode names
        # very well
        for directory in directories:
            directory_path = to_bytes(directory['src'],
                                      errors='surrogate_or_strict')
            archive_path = to_bytes(directory['dest'],
                                    errors='surrogate_or_strict')

            encoded_path = to_text(base64.b64encode(archive_path),
                                   errors='surrogate_or_strict')
            zip_file.write(directory_path, encoded_path, zipfile.ZIP_DEFLATED)

        for file in files:
            file_path = to_bytes(file['src'], errors='surrogate_or_strict')
            archive_path = to_bytes(file['dest'], errors='surrogate_or_strict')

            encoded_path = to_text(base64.b64encode(archive_path),
                                   errors='surrogate_or_strict')
            zip_file.write(file_path, encoded_path, zipfile.ZIP_DEFLATED)

        return zip_file_path
Ejemplo n.º 8
0
def run_commands(module, commands, check_rc=True):
    responses = list()
    connection = get_connection(module)

    for cmd in to_list(commands):
        if isinstance(cmd, dict):
            command = cmd['command']
            prompt = cmd['prompt']
            answer = cmd['answer']
        else:
            command = cmd
            prompt = None
            answer = None

        try:
            out = connection.get(command, prompt, answer)
        except ConnectionError as exc:
            module.fail_json(msg=to_text(exc))

        try:
            out = to_text(out, errors='surrogate_or_strict')
        except UnicodeError:
            module.fail_json(msg=u'Failed to decode output from %s: %s' %
                             (cmd, to_text(out)))

        responses.append(out)

    return responses
Ejemplo n.º 9
0
def handle_errors(module, exception, method_name, parameters):

    if not isinstance(exception, ClientError):
        module.fail_json_aws(
            exception,
            msg="Unexpected failure for method {0} with parameters {1}".format(
                method_name, parameters))

    changed = True
    error_code = exception.response['Error']['Code']
    if method_name == 'modify_db_instance' and error_code == 'InvalidParameterCombination':
        if 'No modifications were requested' in to_text(exception):
            changed = False
        elif 'ModifyDbCluster API' in to_text(exception):
            module.fail_json_aws(
                exception,
                msg=
                'It appears you are trying to modify attributes that are managed at the cluster level. Please see rds_cluster'
            )
        else:
            module.fail_json_aws(exception,
                                 msg='Unable to {0}'.format(
                                     get_rds_method_attribute(
                                         method_name,
                                         module).operation_description))
    elif method_name == 'promote_read_replica' and error_code == 'InvalidDBInstanceState':
        if 'DB Instance is not a read replica' in to_text(exception):
            changed = False
        else:
            module.fail_json_aws(exception,
                                 msg='Unable to {0}'.format(
                                     get_rds_method_attribute(
                                         method_name,
                                         module).operation_description))
    elif method_name == 'create_db_instance' and exception.response['Error'][
            'Code'] == 'InvalidParameterValue':
        accepted_engines = [
            'aurora', 'aurora-mysql', 'aurora-postgresql', 'mariadb', 'mysql',
            'oracle-ee', 'oracle-se', 'oracle-se1', 'oracle-se2', 'postgres',
            'sqlserver-ee', 'sqlserver-ex', 'sqlserver-se', 'sqlserver-web'
        ]
        if parameters.get('Engine') not in accepted_engines:
            module.fail_json_aws(
                exception,
                msg='DB engine {0} should be one of {1}'.format(
                    parameters.get('Engine'), accepted_engines))
        else:
            module.fail_json_aws(exception,
                                 msg='Unable to {0}'.format(
                                     get_rds_method_attribute(
                                         method_name,
                                         module).operation_description))
    else:
        module.fail_json_aws(
            exception,
            msg='Unable to {0}'.format(
                get_rds_method_attribute(method_name,
                                         module).operation_description))

    return changed
Ejemplo n.º 10
0
    def set_cli_prompt_context(self):
        """
        Make sure we are in the operational cli mode
        :return: None
        """
        if self._connection.connected:
            out = self._connection.get_prompt()

            if out is None:
                raise AnsibleConnectionFailure(
                    message=
                    u'cli prompt is not identified from the last received'
                    u' response window: %s' %
                    self._connection._last_recv_window)

            prompt = to_text(out, errors='surrogate_then_replace').strip()
            while prompt.endswith(']'):
                self._connection.queue_message(
                    'vvvv', 'wrong context, sending return to device')
                if prompt.startswith('[*'):
                    self._connection.exec_command(
                        'clear configuration candidate')
                self._connection.exec_command('return')
                out = self._connection.get_prompt()
                prompt = to_text(out, errors='surrogate_then_replace').strip()
Ejemplo n.º 11
0
def equal_values(v1, v2):
    """
    Checks whether types and content of two values are the same. In case of complex objects, the method might be
    called recursively.

    :param v1: first value
    :param v2: second value
    :return: True if types and content of passed values are equal. Otherwise, returns False.
    :rtype: bool
    """

    # string-like values might have same text but different types, so checking them separately
    if is_string(v1) and is_string(v2):
        return to_text(v1) == to_text(v2)

    if type(v1) != type(v2):
        return False
    value_type = type(v1)

    if value_type == list:
        return equal_lists(v1, v2)
    elif value_type == dict:
        return equal_dicts(v1, v2)
    else:
        return v1 == v2
Ejemplo n.º 12
0
def get_defaults_flag(module):
    connection = get_connection(module)
    try:
        out = connection.get_defaults_flag()
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
    return to_text(out, errors='surrogate_then_replace').strip()
Ejemplo n.º 13
0
    def load_config(self, path):
        self.path = path
        self._connect()
        # load in file_mode
        if self.module.params['file_mode']:
            try:
                f = open(self.module.params['config_file'], 'r')
                running = f.read()
                f.close()
            except IOError as e:
                self.module.fail_json(
                    msg='Error reading configuration file. %s' % to_text(e),
                    exception=traceback.format_exc())
            self.forti_device.load_config(config_text=running, path=path)

        else:
            # get  config
            try:
                self.forti_device.load_config(path=path)
            except Exception as e:
                self.forti_device.close()
                self.module.fail_json(msg='Error reading running config. %s' %
                                      to_text(e),
                                      exception=traceback.format_exc())

        # set configs in object
        self.result[
            'running_config'] = self.forti_device.running_config.to_text()
        self.candidate_config = self.forti_device.candidate_config

        # backup if needed
        if self.module.params['backup']:
            backup(self.module, self.forti_device.running_config.to_text())
Ejemplo n.º 14
0
 def default(self, o):
     if getattr(o, '__ENCRYPTED__', False):
         # vault object
         value = {
             '__ansible_vault':
             to_text(o._ciphertext,
                     errors='surrogate_or_strict',
                     nonstring='strict')
         }
     elif getattr(o, '__UNSAFE__', False):
         # unsafe object, this will never be triggered, see ``AnsibleJSONEncoder.iterencode``
         value = {
             '__ansible_unsafe':
             to_text(o, errors='surrogate_or_strict', nonstring='strict')
         }
     elif isinstance(o, Mapping):
         # hostvars and other objects
         value = dict(o)
     elif isinstance(o, (datetime.date, datetime.datetime)):
         # date object
         value = o.isoformat()
     else:
         # use default encoder
         value = super(AnsibleJSONEncoder, self).default(o)
     return value
Ejemplo n.º 15
0
    def parse_rpc_error(self, rpc_error):
        if self.check_rc:
            try:
                error_root = fromstring(rpc_error)
                root = Element('root')
                root.append(error_root)

                error_list = root.findall('.//nc:rpc-error', NS_MAP)
                if not error_list:
                    raise ConnectionError(to_text(rpc_error, errors='surrogate_then_replace'))

                warnings = []
                for error in error_list:
                    message_ele = error.find('./nc:error-message', NS_MAP)

                    if message_ele is None:
                        message_ele = error.find('./nc:error-info', NS_MAP)

                    message = message_ele.text if message_ele is not None else None

                    severity = error.find('./nc:error-severity', NS_MAP).text

                    if severity == 'warning' and self.ignore_warning and message is not None:
                        warnings.append(message)
                    else:
                        raise ConnectionError(to_text(rpc_error, errors='surrogate_then_replace'))
                return warnings
            except XMLSyntaxError:
                raise ConnectionError(rpc_error)
Ejemplo n.º 16
0
 def get_distribution(self, task_vars):
     distribution = {}
     display.debug(
         '{action}: running setup module to get distribution'.format(
             action=self._task.action))
     module_output = self._execute_module(
         task_vars=task_vars,
         module_name='setup',
         module_args={'gather_subset': 'min'})
     try:
         if module_output.get('failed', False):
             raise AnsibleError(
                 'Failed to determine system distribution. {0}, {1}'.format(
                     to_native(module_output['module_stdout']).strip(),
                     to_native(module_output['module_stderr']).strip()))
         distribution['name'] = module_output['ansible_facts'][
             'ansible_distribution'].lower()
         distribution['version'] = to_text(
             module_output['ansible_facts']
             ['ansible_distribution_version'].split('.')[0])
         distribution['family'] = to_text(
             module_output['ansible_facts']['ansible_os_family'].lower())
         display.debug("{action}: distribution: {dist}".format(
             action=self._task.action, dist=distribution))
         return distribution
     except KeyError as ke:
         raise AnsibleError(
             'Failed to get distribution information. Missing "{0}" in output.'
             .format(ke.args[0]))
Ejemplo n.º 17
0
    def run(self, terms, variables=None, **kwargs):

        self.set_options(direct=kwargs)

        ret = []
        for term in terms:
            display.vvvv("url lookup connecting to %s" % term)
            try:
                response = open_url(
                    term,
                    validate_certs=self.get_option('validate_certs'),
                    use_proxy=self.get_option('use_proxy'),
                    url_username=self.get_option('username'),
                    url_password=self.get_option('password'),
                    headers=self.get_option('headers'))
            except HTTPError as e:
                raise AnsibleError("Received HTTP error for %s : %s" %
                                   (term, to_native(e)))
            except URLError as e:
                raise AnsibleError("Failed lookup url for %s : %s" %
                                   (term, to_native(e)))
            except SSLValidationError as e:
                raise AnsibleError(
                    "Error validating the server's certificate for %s: %s" %
                    (term, to_native(e)))
            except ConnectionError as e:
                raise AnsibleError("Error connecting to %s: %s" %
                                   (term, to_native(e)))

            if self.get_option('split_lines'):
                for line in response.read().splitlines():
                    ret.append(to_text(line))
            else:
                ret.append(to_text(response.read()))
        return ret
Ejemplo n.º 18
0
 def formatresponse(self, res, vdom=None):
     if vdom == "global":
         resp = json.loads(to_text(res))[0]
         resp['vdom'] = "global"
     else:
         resp = json.loads(to_text(res))
     return resp
Ejemplo n.º 19
0
def load_config(module, commands, commit=False, comment=None):
    connection = get_connection(module)

    try:
        out = connection.edit_config(commands)
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc))

    diff = None
    if module._diff:
        out = connection.get('compare')
        out = to_text(out, errors='surrogate_or_strict')

        if not out.startswith('No changes'):
            out = connection.get('show')
            diff = to_text(out, errors='surrogate_or_strict').strip()

    if commit:
        try:
            out = connection.commit(comment)
        except ConnectionError:
            connection.discard_changes()
            module.fail_json(msg='commit failed: %s' % out)

    if not commit:
        connection.discard_changes()
    else:
        connection.get('exit')

    if diff:
        return diff
Ejemplo n.º 20
0
def openssl_get_csr_identifiers(openssl_binary, module, csr_filename):
    '''
    Return a set of requested identifiers (CN and SANs) for the CSR.
    Each identifier is a pair (type, identifier), where type is either
    'dns' or 'ip'.
    '''
    openssl_csr_cmd = [openssl_binary, "req", "-in", csr_filename, "-noout", "-text"]
    dummy, out, dummy = module.run_command(openssl_csr_cmd, check_rc=True)

    identifiers = set([])
    common_name = re.search(r"Subject:.* CN\s?=\s?([^\s,;/]+)", to_text(out, errors='surrogate_or_strict'))
    if common_name is not None:
        identifiers.add(('dns', common_name.group(1)))
    subject_alt_names = re.search(
        r"X509v3 Subject Alternative Name: (?:critical)?\n +([^\n]+)\n",
        to_text(out, errors='surrogate_or_strict'), re.MULTILINE | re.DOTALL)
    if subject_alt_names is not None:
        for san in subject_alt_names.group(1).split(", "):
            if san.lower().startswith("dns:"):
                identifiers.add(('dns', san[4:]))
            elif san.lower().startswith("ip:"):
                identifiers.add(('ip', _normalize_ip(san[3:])))
            elif san.lower().startswith("ip address:"):
                identifiers.add(('ip', _normalize_ip(san[11:])))
            else:
                raise ModuleFailException('Found unsupported SAN identifier "{0}"'.format(san))
    return identifiers
Ejemplo n.º 21
0
def _sign_request_openssl(openssl_binary, module, payload64, protected64, key_data):
    openssl_sign_cmd = [openssl_binary, "dgst", "-{0}".format(key_data['hash']), "-sign", key_data['key_file']]
    sign_payload = "{0}.{1}".format(protected64, payload64).encode('utf8')
    dummy, out, dummy = module.run_command(openssl_sign_cmd, data=sign_payload, check_rc=True, binary_data=True)

    if key_data['type'] == 'ec':
        dummy, der_out, dummy = module.run_command(
            [openssl_binary, "asn1parse", "-inform", "DER"],
            data=out, binary_data=True)
        expected_len = 2 * key_data['point_size']
        sig = re.findall(
            r"prim:\s+INTEGER\s+:([0-9A-F]{1,%s})\n" % expected_len,
            to_text(der_out, errors='surrogate_or_strict'))
        if len(sig) != 2:
            raise ModuleFailException(
                "failed to generate Elliptic Curve signature; cannot parse DER output: {0}".format(
                    to_text(der_out, errors='surrogate_or_strict')))
        sig[0] = (expected_len - len(sig[0])) * '0' + sig[0]
        sig[1] = (expected_len - len(sig[1])) * '0' + sig[1]
        out = binascii.unhexlify(sig[0]) + binascii.unhexlify(sig[1])

    return {
        "protected": protected64,
        "payload": payload64,
        "signature": nopad_b64(to_bytes(out)),
    }
Ejemplo n.º 22
0
    def run(self, terms, variables=None, **kwargs):
        self.set_options(direct=kwargs)

        ret = []

        for term in terms:
            auth = to_text(
                base64.b64encode(
                    to_bytes('{0}:{1}'.format(self.get_option('cpm_username'),
                                              self.get_option('cpm_password')),
                             errors='surrogate_or_strict')))

            if self.get_option('use_https') is True:
                protocol = "https://"
            else:
                protocol = "http://"

            if (term == 'temperature'):
                fullurl = ("%s%s/api/v2/status/temperature" %
                           (protocol, self.get_option('cpm_url')))
            elif (term == 'firmware'):
                fullurl = ("%s%s/api/v2/status/firmware" %
                           (protocol, self.get_option('cpm_url')))
            elif (term == 'status'):
                fullurl = ("%s%s/api/v2/status/status" %
                           (protocol, self.get_option('cpm_url')))
            elif (term == 'alarms'):
                fullurl = ("%s%s/api/v2/status/alarms" %
                           (protocol, self.get_option('cpm_url')))
            else:
                raise AnsibleError("Status command not recognized %s " %
                                   (term))

            try:
                response = open_url(
                    fullurl,
                    validate_certs=self.get_option('validate_certs'),
                    use_proxy=self.get_option('use_proxy'),
                    headers={
                        'Content-Type': 'application/json',
                        'Authorization': "Basic %s" % auth
                    })
            except HTTPError as e:
                raise AnsibleError("Received HTTP error for %s : %s" %
                                   (fullurl, to_native(e)))
            except URLError as e:
                raise AnsibleError("Failed lookup url for %s : %s" %
                                   (fullurl, to_native(e)))
            except SSLValidationError as e:
                raise AnsibleError(
                    "Error validating the server's certificate for %s: %s" %
                    (fullurl, to_native(e)))
            except ConnectionError as e:
                raise AnsibleError("Error connecting to %s: %s" %
                                   (fullurl, to_native(e)))

            ret.append(to_text(response.read()))

        return ret
Ejemplo n.º 23
0
    def has_changed(self,
                    want_dict,
                    current_dict,
                    only_keys=None,
                    skip_diff_for_keys=None):
        result = False
        for key, value in want_dict.items():

            # Optionally limit by a list of keys
            if only_keys and key not in only_keys:
                continue

            # Skip None values
            if value is None:
                continue

            if key in current_dict:
                if isinstance(value, (int, float, long, complex)):

                    # ensure we compare the same type
                    if isinstance(value, int):
                        current_dict[key] = int(current_dict[key])
                    elif isinstance(value, float):
                        current_dict[key] = float(current_dict[key])
                    elif isinstance(value, long):
                        current_dict[key] = long(current_dict[key])
                    elif isinstance(value, complex):
                        current_dict[key] = complex(current_dict[key])

                    if value != current_dict[key]:
                        if skip_diff_for_keys and key not in skip_diff_for_keys:
                            self.result['diff']['before'][key] = current_dict[
                                key]
                            self.result['diff']['after'][key] = value
                        result = True
                else:
                    before_value = to_text(current_dict[key])
                    after_value = to_text(value)

                    if self.case_sensitive_keys and key in self.case_sensitive_keys:
                        if before_value != after_value:
                            if skip_diff_for_keys and key not in skip_diff_for_keys:
                                self.result['diff']['before'][
                                    key] = before_value
                                self.result['diff']['after'][key] = after_value
                            result = True

                    # Test for diff in case insensitive way
                    elif before_value.lower() != after_value.lower():
                        if skip_diff_for_keys and key not in skip_diff_for_keys:
                            self.result['diff']['before'][key] = before_value
                            self.result['diff']['after'][key] = after_value
                        result = True
            else:
                if skip_diff_for_keys and key not in skip_diff_for_keys:
                    self.result['diff']['before'][key] = None
                    self.result['diff']['after'][key] = to_text(value)
                result = True
        return result
Ejemplo n.º 24
0
 def _run(self, args, stdin=None, expected_rc=0):
     p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE)
     out, err = p.communicate(to_bytes(stdin))
     rc = p.wait()
     if rc != expected_rc:
         raise LPassException(err)
     return to_text(out, errors='surrogate_or_strict'), to_text(
         err, errors='surrogate_or_strict')
Ejemplo n.º 25
0
 def json(self):
     if not self.body:
         if "body" in self.info:
             return json.loads(to_text(self.info["body"]))
         return None
     try:
         return json.loads(to_text(self.body))
     except ValueError:
         return None
Ejemplo n.º 26
0
    def run_commands(self, commands, check_rc=True):
        if commands is None:
            raise ValueError("'commands' value is required")

        headers = {'Content-Type': 'application/json'}
        responses = list()
        for cmd in to_list(commands):
            if not isinstance(cmd, Mapping):
                cmd = {'command': cmd}

            cmd['command'] = strip_run_script_cli2json(cmd['command'])

            output = cmd.pop('output', None)
            if output and output not in self.get_option_values().get('output'):
                raise ValueError(
                    "'output' value is %s is invalid. Valid values are %s" %
                    (output, ','.join(self.get_option_values().get('output'))))

            data = request_builder(cmd['command'])

            response, response_data = self.connection.send(
                '/jsonrpc',
                data,
                cookies=self._auth_token,
                headers=headers,
                method='POST')
            try:
                response_data = json.loads(to_text(response_data.getvalue()))
            except ValueError:
                raise ConnectionError(
                    'Response was not valid JSON, got {0}'.format(
                        to_text(response_data.getvalue())))

            if response_data.get('error', None):
                raise ConnectionError("Request Error, got {0}".format(
                    response_data['error']))
            if not response_data.get('result', None):
                raise ConnectionError(
                    "Request Error, got {0}".format(response_data))

            response_data = response_data['result']

            if output and output == 'text':
                statusOut = getKeyInResponse(response_data, 'status')
                cliOut = getKeyInResponse(response_data, 'CLIoutput')
                if statusOut == "ERROR":
                    raise ConnectionError(
                        "Command error({1}) for request {0}".format(
                            cmd['command'], cliOut))
                if cliOut is None:
                    raise ValueError(
                        "Response for request {0} doesn't have the CLIoutput field, got {1}"
                        .format(cmd['command'], response_data))
                response_data = cliOut

            responses.append(response_data)
        return responses
Ejemplo n.º 27
0
    def run(self, terms, variables, **kwargs):
        '''
        terms contain any number of keys to be retrieved.
        If terms is None, all keys from the database are returned
        with their values, and if term ends in an asterisk, we
        start searching there

        The LMDB database defaults to 'ansible.mdb' if Ansible's
        variable 'lmdb_kv_db' is not set:

              vars:
                - lmdb_kv_db: "jp.mdb"
        '''

        if HAVE_LMDB is False:
            raise AnsibleError(
                "Can't LOOKUP(lmdb_kv): this module requires lmdb to be installed"
            )

        db = variables.get('lmdb_kv_db', None)
        if db is None:
            db = kwargs.get('db', 'ansible.mdb')
        db = str(db)

        try:
            env = lmdb.open(db, readonly=True)
        except Exception as e:
            raise AnsibleError("LMDB can't open database %s: %s" %
                               (db, to_native(e)))

        ret = []
        if len(terms) == 0:
            with env.begin() as txn:
                cursor = txn.cursor()
                cursor.first()
                for key, value in cursor:
                    ret.append((to_text(key), to_native(value)))

        else:
            for term in terms:
                with env.begin() as txn:
                    if term.endswith('*'):
                        cursor = txn.cursor()
                        prefix = term[:-1]  # strip asterisk
                        cursor.set_range(to_text(term).encode())
                        while cursor.key().startswith(
                                to_text(prefix).encode()):
                            for key, value in cursor:
                                ret.append((to_text(key), to_native(value)))
                            cursor.next()
                    else:
                        value = txn.get(to_text(term).encode())
                        if value is not None:
                            ret.append(to_native(value))

        return ret
Ejemplo n.º 28
0
def run_commands(module, commands, check_rc=True):
    responses = list()
    commands = to_commands(module, to_list(commands))
    for cmd in commands:
        cmd = module.jsonify(cmd)
        rc, out, err = exec_command(module, cmd)
        if check_rc and rc != 0:
            module.fail_json(msg=to_text(err, errors='surrogate_then_replace'), rc=rc)
        responses.append(to_text(out, errors='surrogate_then_replace'))
    return responses
Ejemplo n.º 29
0
def run_commands(module, commands, check_rc=True):
    responses = list()
    commands = to_commands(module, to_list(commands))
    for cmd in commands:
        cmd = module.jsonify(cmd)
        rc, out, err = exec_command(module, cmd)
        if check_rc and rc != 0:
            raise F5ModuleError(to_text(err, errors='surrogate_then_replace'))
        result = to_text(out, errors='surrogate_then_replace')
        responses.append(result)
    return responses
Ejemplo n.º 30
0
def load_config(module, commands):
    rc, out, err = exec_command(module, 'configure terminal')
    if rc != 0:
        module.fail_json(msg='unable to enter configuration mode', err=to_text(err, errors='surrogate_or_strict'))

    for command in to_list(commands):
        if command == 'end':
            continue
#        cmd = {'command': command, 'prompt': WARNING_PROMPTS_RE, 'answer': 'yes'}
        rc, out, err = exec_command(module, command)
        if rc != 0:
            module.fail_json(msg=to_text(err, errors='surrogate_or_strict'), command=command, rc=rc)
    exec_command(module, 'end')