Ejemplo n.º 1
0
    def _validate_options(self):
        CliCommand._validate_options(self)

        if not self.options.profile:
            print(_("No profile specified."))
            self.parser.print_help()
            sys.exit(1)

        if not self.options.report_path:
            print(_("No report location specified."))
            self.parser.print_help()
            sys.exit(1)

        if self.options.ansible_forks:
            try:
                if int(self.options.ansible_forks) <= 0:
                    print(_("--ansible-forks can only be a positive integer."))
                    self.parser.print_help()
                    sys.exit(1)
            except ValueError:
                print(_("--ansible-forks can only be a positive integer."))
                self.parser.print_help()
                sys.exit(1)

        # perform fact validation
        input_facts = self.options.facts
        assert isinstance(input_facts, list)

        if input_facts and os.path.isfile(input_facts[0]):
            input_facts = _read_in_file(input_facts[0])

        self.facts_to_collect = facts.expand_facts(input_facts)

        if self.options.scan_dirs == []:
            self.options.scan_dirs = ['/', '/opt', '/app', '/home', '/usr']
        elif os.path.isfile(self.options.scan_dirs[0]):
            self.options.scan_dirs = \
                _read_in_file(self.options.scan_dirs[0])
        else:
            assert isinstance(self.options.scan_dirs, list)
        # check that all values in scan_dirs are valid abs paths
        invalid_paths = utilities.check_path_validity(self.options.scan_dirs)
        if invalid_paths != []:
            print(
                _("Invalid paths were supplied to the --scan-dirs option: " +
                  ",".join(invalid_paths)))
            self.parser.print_help()
            sys.exit(1)
Ejemplo n.º 2
0
    def _validate_options(self):
        CliCommand._validate_options(self)

        if not self.options.report_path:
            print(_("No report location specified."))
            self.parser.print_help()
            sys.exit(1)

        normalized_path = os.path.normpath(self.options.report_path)
        if not os.path.isfile(normalized_path):
            print(_('Report location is invalid.'))
            sys.exit(1)

        # perform fact validation
        facts = self.options.facts
        if facts == [] or facts == ['default']:
            self.facts_to_hash = list(utilities.SENSITIVE_FACTS_TUPLE)
        elif os.path.isfile(facts[0]):
            self.facts_to_hash = _read_in_file(facts[0])
        else:
            assert isinstance(facts, list)
            self.facts_to_hash = facts
        # check facts_to_hash is subset of utilities.DEFAULT_FACTS
        all_facts = utilities.DEFAULT_FACTS
        facts_to_hash_set = set(self.facts_to_hash)
        if not facts_to_hash_set.issubset(all_facts):
            invalid_facts = facts_to_hash_set.difference(all_facts)
            print(
                _("Invalid facts were supplied to the command: " +
                  ",".join(invalid_facts)))
            self.parser.print_help()
            sys.exit(1)
Ejemplo n.º 3
0
    def _validate_options(self):
        CliCommand._validate_options(self)

        if not self.options.report_path:
            print(_("No report location specified."))
            self.parser.print_help()
            sys.exit(1)

        normalized_path = os.path.normpath(self.options.report_path)
        if not os.path.isfile(normalized_path):
            print(_('Report location is invalid.'))
            sys.exit(1)

        # perform fact validation
        input_facts = self.options.facts
        if input_facts == [] or input_facts == ['default']:
            self.facts_to_hash = facts.SENSITIVE_FACTS
        elif os.path.isfile(input_facts[0]):
            self.facts_to_hash = set(_read_in_file(input_facts[0]))
        else:
            assert isinstance(input_facts, list)
            self.facts_to_hash = set(input_facts)
        # check facts_to_hash is subset of facts.ALL_FACTS
        if not self.facts_to_hash.issubset(facts.ALL_FACTS):
            invalid_facts = self.facts_to_hash.difference(facts.ALL_FACTS)
            print(
                _("Invalid facts were supplied to the command: " +
                  ",".join(invalid_facts)))
            self.parser.print_help()
            sys.exit(1)
Ejemplo n.º 4
0
    def _do_command(self):
        vault = get_vault(self.options.vaultfile)
        hosts_list = self.options.hosts
        profiles_list = []
        ssh_port = 22

        if hasattr(self.options, 'sshport') \
           and self.options.sshport is not None:
            ssh_port = utilities.validate_port(self.options.sshport)

        if os.path.isfile(utilities.PROFILES_PATH):
            profiles_list = vault.load_as_json(utilities.PROFILES_PATH)
            profile_found = profile_exists(profiles_list, self.options.name)
            if profile_found:
                print(_("Profile '%s' already exists.") % self.options.name)
                sys.exit(1)

        range_list = hosts_list

        # pylint: disable=len-as-condition
        if len(hosts_list) > 0 and os.path.isfile(hosts_list[0]):
            range_list = _read_in_file(hosts_list[0])

        _check_range_validity(range_list)

        if not os.path.isfile(utilities.CREDENTIALS_PATH):
            print(_('No credentials exist yet.'))
            sys.exit(1)

        creds = []
        cred_list = vault.load_as_json(utilities.CREDENTIALS_PATH)
        for auth in self.options.auth:
            for auth_item in auth.strip().split(","):
                valid = False
                for cred in cred_list:
                    if cred.get('name') == auth:
                        valid = True
                        # add the uuids of credentials
                        store_cred = {'id': cred.get('id'),
                                      'name': cred.get('name')}
                        creds.append(store_cred)

                if not valid:
                    print("Auth " + auth_item + " does not exist")
                    sys.exit(1)

        new_profile = OrderedDict([("name", self.options.name),
                                   ("hosts", range_list),
                                   ("ssh_port", str(ssh_port)),
                                   ("auth", creds)])

        _save_profile(vault, new_profile, profiles_list)
Ejemplo n.º 5
0
    def _do_command(self):
        # pylint: disable=too-many-locals
        # pylint: disable=too-many-branches
        vault, vault_pass = get_vault_and_password(self.options.vaultfile)
        profile_found = False
        profile_auth_list = []
        profile_ranges = []
        profile_port = 22
        profile = self.options.profile
        facts = self.options.facts
        forks = self.options.ansible_forks \
            if self.options.ansible_forks else '50'
        report_path = os.path.abspath(
            os.path.normpath(self.options.report_path))

        # Checks if profile exists and stores information
        # about that profile for later use.
        if not os.path.isfile(utilities.PROFILES_PATH):
            print(_('No profiles exist yet.'))
            sys.exit(1)

        if not os.path.isfile(utilities.CREDENTIALS_PATH):
            print(_('No auth credentials exist yet.'))
            sys.exit(1)

        profiles_list = vault.load_as_json(utilities.PROFILES_PATH)
        for curr_profile in profiles_list:
            if self.options.profile == curr_profile.get('name'):
                profile_found = True
                profile_ranges = curr_profile.get('hosts')
                profile_auths = curr_profile.get('auth')
                profile_port = curr_profile.get('ssh_port')
                cred_list = vault.load_as_json(utilities.CREDENTIALS_PATH)
                for auth in profile_auths:
                    for cred in cred_list:
                        if auth.get('id') == cred.get('id'):
                            profile_auth_list.append(cred)
                break

        if not profile_found:
            print(_("Invalid profile. Create profile first"))
            sys.exit(1)

        # reset is used when the profile has just been created
        # or freshly updated.
        if self.options.reset:
            success_auths, success_hosts, best_map, success_map, \
                success_port_map = _create_ping_inventory(vault, vault_pass,
                                                          profile_ranges,
                                                          profile_port,
                                                          profile_auth_list,
                                                          forks)

            if not len(success_auths):  # pylint: disable=len-as-condition
                print(_('All auths are invalid for this profile'))
                sys.exit(1)

            _create_hosts_auths_file(success_map, profile)

            _create_main_inventory(vault, success_hosts, success_port_map,
                                   best_map, profile)

        elif not os.path.isfile('data/' + profile + '_hosts'):
            print("Profile '" + profile + "' has not been processed. " +
                  "Please use --reset with profile first.")
            sys.exit(1)

        if facts == ['default']:
            facts_to_collect = 'default'
        elif os.path.isfile(facts[0]):
            facts_to_collect = _read_in_file(facts[0])
        else:
            assert isinstance(facts, list)
            facts_to_collect = facts

        ansible_vars = {
            'facts_to_collect': facts_to_collect,
            'report_path': report_path
        }

        cmd_string = ('ansible-playbook rho_playbook.yml '
                      '-i data/{profile}_hosts.yml -v -f {forks} '
                      '--ask-vault-pass '
                      '--extra-vars \'{vars}\'').format(
                          profile=profile,
                          forks=forks,
                          vars=json.dumps(ansible_vars))

        # process finally runs ansible on the
        # playbook and inventories thus created.
        print('Running:', cmd_string)
        run_ansible_with_vault(cmd_string, vault_pass)

        print(
            _("Scanning has completed. The mapping has been"
              " stored in file '" + self.options.profile +
              "_host_auth_map'. The"
              " facts have been stored in '" + report_path + "'"))
Ejemplo n.º 6
0
    def _validate_options(self):
        CliCommand._validate_options(self)

        if not self.options.profile:
            print(_("No profile specified."))
            self.parser.print_help()
            sys.exit(1)

        if not self.options.report_path:
            print(_("No report location specified."))
            self.parser.print_help()
            sys.exit(1)

        if self.options.ansible_forks:
            try:
                if int(self.options.ansible_forks) <= 0:
                    print(_("--ansible-forks can only be a positive integer."))
                    self.parser.print_help()
                    sys.exit(1)
            except ValueError:
                print(_("--ansible-forks can only be a positive integer."))
                self.parser.print_help()
                sys.exit(1)

        # perform fact validation
        facts = self.options.facts
        if facts == []:
            self.facts_to_collect = list(utilities.RHEL_FACTS +
                                         utilities.CONNECTION_FACTS_TUPLE)
        elif facts == ['default'] or facts == ['all']:
            self.facts_to_collect = list(utilities.DEFAULT_FACTS)
        elif facts == ['jboss']:
            self.facts_to_collect = list(utilities.JBOSS_FACTS +
                                         utilities.CONNECTION_FACTS_TUPLE)
        elif facts == ['rhel']:
            self.facts_to_collect = list(utilities.RHEL_FACTS +
                                         utilities.CONNECTION_FACTS_TUPLE)
        elif os.path.isfile(facts[0]):
            self.facts_to_collect = _read_in_file(facts[0])
        else:
            assert isinstance(facts, list)
            self.facts_to_collect = facts
        # check facts_to_collect is subset of utilities.DEFAULT_FACTS
        all_facts = utilities.DEFAULT_FACTS
        facts_to_collect_set = set(self.facts_to_collect)
        if not facts_to_collect_set.issubset(all_facts):
            invalid_facts = facts_to_collect_set.difference(all_facts)
            print(_("Invalid facts were supplied to scan command: " +
                    ",".join(invalid_facts)))
            self.parser.print_help()
            sys.exit(1)

        if self.options.scan_dirs == []:
            self.options.scan_dirs = ['/', '/opt', '/app', '/home', '/usr']
        elif os.path.isfile(self.options.scan_dirs[0]):
            self.options.scan_dirs = \
                _read_in_file(self.options.scan_dirs[0])
        else:
            assert isinstance(self.options.scan_dirs, list)
        # check that all values in scan_dirs are valid abs paths
        invalid_paths = utilities.check_path_validity(self.options.scan_dirs)
        if invalid_paths != []:
            print(_("Invalid paths were supplied to the --scan-dirs option: " +
                    ",".join(invalid_paths)))
            self.parser.print_help()
            sys.exit(1)
Ejemplo n.º 7
0
    def _do_command(self):
        # pylint: disable=too-many-locals, too-many-branches
        # pylint: disable=too-many-statements, too-many-nested-blocks
        vault = get_vault(self.options.vaultfile)
        cred_list = []
        profiles_list = []
        range_list = []
        profile_found = False
        auth_found = False

        if not os.path.isfile(utilities.CREDENTIALS_PATH):
            print(_('No credentials exist yet.'))
            sys.exit(1)

        if not os.path.isfile(utilities.PROFILES_PATH):
            print(_('No profiles exist yet.'))
            sys.exit(1)

        cred_list = vault.load_as_json(utilities.CREDENTIALS_PATH)
        profiles_list = vault.load_as_json(utilities.PROFILES_PATH)

        if self.options.hosts:
            hosts_list = self.options.hosts
            range_list = hosts_list
            # pylint: disable=len-as-condition
            if len(hosts_list) > 0 and os.path.isfile(hosts_list[0]):
                range_list = _read_in_file(hosts_list[0])

            # makes sure the hosts passed in are in a format Ansible
            # understands.
            _check_range_validity(range_list)

        for curr_profile in profiles_list:
            if curr_profile.get('name') == self.options.name:
                profile_found = True
                if self.options.hosts:
                    curr_profile['hosts'] = range_list

                if self.options.sshport:
                    curr_profile['ssh_port'] = str(
                        utilities.validate_port(self.options.sshport))

                if self.options.auth:
                    new_auths = []
                    auth_list = self.options.auth
                    for auth in auth_list:
                        for cred in cred_list:
                            if auth == cred.get('name'):
                                auth_found = True
                                store_cred = {'id': cred.get('id'),
                                              'name': cred.get('name')}
                                new_auths.append(store_cred)
                    if not auth_found:
                        print(_("Auths do not exist."))
                        sys.exit(1)

                    curr_profile['auth'] = new_auths
                break

        if not profile_found:
            print(_("Profile '%s' does not exist.") % self.options.name)
            sys.exit(1)

        vault.dump_as_json_to_file(profiles_list, utilities.PROFILES_PATH)
        print(_("Profile '%s' edited" % self.options.name))