Beispiel #1
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), GET,
                         report.REPORT_URI, [codes.ok])
     id_group = self.parser.add_mutually_exclusive_group(required=True)
     id_group.add_argument('--scan-job',
                           dest='scan_job_id',
                           metavar='SCAN_JOB_ID',
                           help=_(messages.REPORT_SCAN_JOB_ID_HELP))
     id_group.add_argument('--report',
                           dest='report_id',
                           metavar='REPORT_ID',
                           help=_(messages.REPORT_REPORT_ID_HELP))
     self.parser.add_argument('--output-file',
                              dest='path',
                              metavar='PATH',
                              help=_(messages.DOWNLOAD_PATH_HELP),
                              required=True)
     self.parser.add_argument('--mask',
                              dest='mask',
                              action='store_true',
                              help=_(messages.REPORT_MASK_HELP),
                              required=False)
     self.min_server_version = '0.9.2'
     self.report_id = None
Beispiel #2
0
    def _validate_args(self):
        CliCommand._validate_args(self)

        if not (self.args.username or self.args.password or self.args.filename
                or self.args.ssh_passphrase or self.args.become_method
                or self.args.become_user or self.args.become_password):
            print(_(messages.CRED_EDIT_NO_ARGS % (self.args.name)))
            self.parser.print_help()
            sys.exit(1)

        # check for existence of credential
        response = request(parser=self.parser,
                           method=GET,
                           path=credential.CREDENTIAL_URI,
                           params={'name': self.args.name},
                           payload=None)
        if response.status_code == codes.ok:  # pylint: disable=no-member
            json_data = response.json()
            count = json_data.get('count', 0)
            if count == 1:
                cred_entry = json_data.get('results')[0]
                self.cred_type = cred_entry['cred_type']
                self.req_path = self.req_path + str(cred_entry['id']) + '/'
            else:
                print(_(messages.CRED_DOES_NOT_EXIST % self.args.name))
                sys.exit(1)
        else:
            print(_(messages.CRED_DOES_NOT_EXIST % self.args.name))
            sys.exit(1)
Beispiel #3
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), PATCH,
                         source.SOURCE_URI, [codes.ok])
     self.parser.add_argument('--name',
                              dest='name',
                              metavar='NAME',
                              help=_(messages.SOURCE_NAME_HELP),
                              required=True)
     self.parser.add_argument('--hosts',
                              dest='hosts',
                              nargs='+',
                              metavar='HOSTS',
                              default=[],
                              help=_(messages.SOURCE_HOSTS_HELP),
                              required=False)
     self.parser.add_argument('--cred',
                              dest='cred',
                              metavar='CRED',
                              nargs='+',
                              default=[],
                              help=_(messages.SOURCE_CREDS_HELP),
                              required=False)
     self.parser.add_argument('--port',
                              dest='port',
                              metavar='PORT',
                              type=validate_port,
                              help=_(messages.SOURCE_PORT_HELP))
Beispiel #4
0
    def main(self):
        """Execute of subcommand operation.

        Method determine whether to display usage or pass input
        to find the best command match. If no match is found the
        usage is displayed
        """
        self.args = self.parser.parse_args()
        setup_logging(self.args.verbosity)
        is_server_cmd = self.args.subcommand == server.SUBCOMMAND
        is_server_logout = is_server_cmd and self.args.action == server.LOGOUT
        is_server_config = is_server_cmd and self.args.action == server.CONFIG

        if not is_server_config:
            # Before attempting to run command, check server location
            server_location = get_server_location()
            if server_location is None or server_location == '':
                log.error(_(messages.SERVER_CONFIG_REQUIRED % PKG_NAME))
                sys.exit(1)

        if read_require_auth():
            if ((not is_server_cmd or is_server_logout)
                    and not read_client_token()):
                log.error(_(messages.SERVER_LOGIN_REQUIRED % PKG_NAME))
                sys.exit(1)

        if self.args.subcommand in self.subcommands:
            subcommand = self.subcommands[self.args.subcommand]
            if self.args.action in subcommand:
                action = subcommand[self.args.action]
                action.main(self.args)
            else:
                self.parser.print_help()
        else:
            self.parser.print_help()
Beispiel #5
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), None, None, [])
     self.parser.add_argument('--host',
                              dest='host',
                              metavar='HOST',
                              help=_(messages.SERVER_CONFIG_HOST_HELP),
                              required=True)
     self.parser.add_argument('--port',
                              dest='port',
                              metavar='PORT',
                              type=validate_port,
                              default=9443,
                              help=_(messages.SERVER_CONFIG_PORT_HELP),
                              required=False)
     self.parser.add_argument('--ssl-verify',
                              dest='ssl_verify',
                              metavar='CERT_PATH',
                              help=_(messages.SERVER_CONFIG_SSL_CERT_HELP),
                              required=False)
     self.parser.add_argument('--use-http',
                              dest='use_http',
                              action='store_true',
                              help=SUPPRESS,
                              required=False)
     self.parser.add_argument('--disable-auth',
                              dest='require_token',
                              action='store_false',
                              help=SUPPRESS,
                              required=False)
Beispiel #6
0
 def __init__(self, subparsers):
     """Create command."""
     super().__init__(
         self.SUBCOMMAND,
         self.ACTION,
         subparsers.add_parser(self.ACTION),
         None,
         None,
         [],
     )
     self.parser.add_argument(
         "--host",
         dest="host",
         metavar="HOST",
         default=DEFAULT_HOST_INSIGHTS_CONFIG,
         type=validate_host,
         help=_(messages.INSIGHTS_CONFIG_HOST_HELP),
         required=False,
     )
     self.parser.add_argument(
         "--port",
         dest="port",
         metavar="PORT",
         type=validate_port,
         default=DEFAULT_PORT_INSIGHTS_CONFIG,
         help=_(messages.INSIGHTS_CONFIG_PORT_HELP),
         required=False,
     )
     self.parser.add_argument("--use-http",
                              dest="use_http",
                              action="store_true",
                              required=False)
Beispiel #7
0
    def __init__(self, subparsers):
        """Create command."""
        # pylint: disable=no-member
        CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                            subparsers.add_parser(self.ACTION), GET,
                            insights.REPORT_URI, [codes.ok])
        input_group = self.parser.add_mutually_exclusive_group(required=True)
        input_group.add_argument('--report',
                                 dest='report_id',
                                 metavar='REPORT_ID',
                                 help=_(messages.INSIGHTS_REPORT_ID_HELP))
        input_group.add_argument('--scan-job',
                                 dest='scan_job_id',
                                 metavar='SCAN_JOB_ID',
                                 help=_(messages.INSIGHTS_SCAN_JOB_ID_HELP))
        input_group.add_argument('--input-file',
                                 dest='input_file',
                                 metavar='INPUT_FILE',
                                 help=_(messages.INSIGHTS_INPUT_GZIP_HELP))

        self.parser.add_argument('--no-gpg',
                                 dest='no_gpg',
                                 action='store_true',
                                 help=_(messages.INSIGHTS_NO_GPG_HELP))
        self.tmp_tar_name = '/tmp/insights_tmp_%s.tar.gz' % (
            time.strftime('%Y%m%d_%H%M%S'))
        # Don't change this when you upgrade versions
        self.min_server_version = '0.9.0'
        self.insights_command = None
        self.report_id = None
Beispiel #8
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), POST,
                         scan.SCAN_URI, [codes.created])
     self.parser.add_argument('--sources',
                              dest='sources',
                              nargs='+',
                              metavar='SOURCES',
                              default=[],
                              help=_(messages.SOURCES_NAME_HELP),
                              required=True)
     self.parser.add_argument('--max-concurrency',
                              dest='max_concurrency',
                              metavar='MAX_CONCURRENCY',
                              type=int,
                              default=50,
                              help=_(messages.SCAN_MAX_CONCURRENCY_HELP))
     self.parser.add_argument('--disable-optional-products',
                              dest='disable_optional_products',
                              nargs='+',
                              choices=scan.OPTIONAL_PRODUCTS,
                              metavar='DISABLE_OPTIONAL_PRODUCTS',
                              help=_(messages.DISABLE_OPT_PRODUCTS_HELP),
                              required=False)
     self.source_ids = []
Beispiel #9
0
 def _handle_response_success(self):
     json_data = self.response.json()
     response_len = len(json_data)
     if self.args.name and response_len == 0:
         print(_(messages.CRED_NOT_FOUND % self.args.name))
         sys.exit(1)
     elif self.args.name and response_len == 1:
         # delete single credential
         entry = json_data[0]
         if self._delete_entry(entry) is False:
             sys.exit(1)
     elif response_len == 0:
         print(_(messages.CRED_NO_CREDS_TO_REMOVE))
         sys.exit(1)
     else:
         # remove all entries
         remove_error = []
         for entry in json_data:
             if self._delete_entry(entry, print_out=False) is False:
                 remove_error.append(entry['name'])
         if remove_error != []:
             cred_err = ','.join(remove_error)
             print(_(messages.CRED_PARTIAL_REMOVE % cred_err))
             sys.exit(1)
         else:
             print(_(messages.CRED_CLEAR_ALL_SUCCESS))
Beispiel #10
0
    def _validate_args(self):
        CliCommand._validate_args(self)

        if not (self.args.username or self.args.password
                or self.args.sudo_password or self.args.filename
                or self.args.ssh_passphrase):
            print(_(messages.CRED_EDIT_NO_ARGS % (self.args.name)))
            self.parser.print_help()
            sys.exit(1)

        if 'filename' in self.args and self.args.filename:
            # check for file existence on system
            self.args.filename = validate_sshkeyfile(self.args.filename,
                                                     self.parser)

        # check for existence of credential
        response = request(parser=self.parser,
                           method=GET,
                           path=credential.CREDENTIAL_URI,
                           params={'name': self.args.name},
                           payload=None)
        if response.status_code == codes.ok:  # pylint: disable=no-member
            json_data = response.json()
            if len(json_data) == 1:
                cred_entry = json_data[0]
                self.cred_type = cred_entry['cred_type']
                self.req_path = self.req_path + str(cred_entry['id']) + '/'
            else:
                print(_(messages.CRED_DOES_NOT_EXIST % self.args.name))
                sys.exit(1)
        else:
            print(_(messages.CRED_DOES_NOT_EXIST % self.args.name))
            sys.exit(1)
Beispiel #11
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), GET,
                         scan.SCAN_URI, [codes.ok])
     group = self.parser.add_mutually_exclusive_group(required=True)
     group.add_argument('--name',
                        dest='name',
                        metavar='NAME',
                        help=_(messages.SCAN_NAME_HELP))
     group.add_argument('--id',
                        dest='id',
                        metavar='ID',
                        help=_(messages.SCAN_JOB_ID_HELP))
     self.parser.add_argument(
         '--status',
         dest='status',
         choices=[
             scan.SCAN_STATUS_CREATED, scan.SCAN_STATUS_PENDING,
             scan.SCAN_STATUS_RUNNING, scan.SCAN_STATUS_PAUSED,
             scan.SCAN_STATUS_CANCELED, scan.SCAN_STATUS_COMPLETED,
             scan.SCAN_STATUS_FAILED
         ],
         metavar='STATUS',
         help=_(messages.SCAN_STATUS_FILTER_HELP),
         required=False)
Beispiel #12
0
def handle_general_errors(response):
    """Handle general errors.

    :param response: The response object.
    :returns: The response object.
    """
    token_expired = {'detail': 'Token has expired'}
    response_data = None
    try:
        response_data = response.json()
    except exception_class:
        pass

    if response.status_code == 401:
        handle_error_response(response)
        log.error(_(messages.SERVER_LOGIN_REQUIRED))
        log.error('$ qpc server login')
        sys.exit(1)
    elif (response.status_code == 400 and response_data == token_expired):
        handle_error_response(response)
        log.error(_(messages.SERVER_LOGIN_REQUIRED))
        log.error('$ qpc server login')
        sys.exit(1)
    elif response.status_code == 500:
        handle_error_response(response)
        log.error(_(messages.SERVER_INTERNAL_ERROR))
        sys.exit(1)

    return response
Beispiel #13
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), PUT,
                         report.ASYNC_MERGE_URI, [codes.created])
     group = self.parser.add_mutually_exclusive_group(required=True)
     group.add_argument('--job-ids',
                        dest='scan_job_ids',
                        nargs='+',
                        metavar='SCAN_JOB_IDS',
                        default=[],
                        help=_(messages.REPORT_SCAN_JOB_IDS_HELP))
     group.add_argument('--report-ids',
                        dest='report_ids',
                        nargs='+',
                        metavar='REPORT_IDS',
                        default=[],
                        help=_(messages.REPORT_REPORT_IDS_HELP))
     group.add_argument('--json-files',
                        dest='json_files',
                        nargs='+',
                        metavar='JSON_FILES',
                        default=[],
                        help=_(messages.REPORT_JSON_FILE_HELP))
     group.add_argument('--json-directory',
                        dest='json_dir',
                        nargs='+',
                        help=_(messages.REPORT_JSON_DIR_HELP))
     self.json = None
     self.report_ids = None
Beispiel #14
0
def get_scan_object_id(parser, name):
    """Grab the scan id from the scan object if it exists.

    :returns Boolean regarding the existence of the object &
    the scan object id
    """
    found = False
    scan_object_id = None
    response = request(parser=parser,
                       method=GET,
                       path=scan.SCAN_URI,
                       params={'name': name},
                       payload=None)
    if response.status_code == codes.ok:  # pylint: disable=no-member
        json_data = response.json()
        count = json_data.get('count', 0)
        results = json_data.get('results', [])
        if count >= 1:
            for result in results:
                if result['name'] == name:
                    scan_object_id = str(result['id']) + '/'
                    found = True
        if not found or count == 0:
            print(_(messages.SCAN_DOES_NOT_EXIST % name))
    else:
        print(_(messages.SCAN_DOES_NOT_EXIST % name))
    return found, scan_object_id
Beispiel #15
0
def request(method, path, params=None, payload=None,
            parser=None, headers=None):
    """Create a generic handler for passing to specific request methods.

    :param method: the request method to execute
    :param path: path after server and port (i.e. /api/v1/credentials)
    :param params: uri encoding params (i.e. ?param1=hello&param2=world)
    :param payload: dictionary of payload to be posted
    :param parser: parser for printing usage on failure
    :param headers: headers to include
    :returns: reponse object
    :raises: AssertionError error if method is not supported
    """
    # grab the cli command for the log if the parser is provided
    log_command = None
    if parser is not None:
        log_command = parser.prog
    req_headers = {}
    token = read_client_token()
    # create the url by adding the path to the configured server location
    url = get_server_location() + path
    if headers:
        req_headers.update(headers)
    if token:
        req_headers['Authorization'] = 'Token {}'.format(token)

    try:
        if method == POST:
            result = handle_general_errors(post(url, payload, req_headers))
        elif method == GET:
            result = handle_general_errors(get(url, params, req_headers))
        elif method == PATCH:
            result = handle_general_errors(patch(url, payload, req_headers))
        elif method == DELETE:
            result = handle_general_errors(delete(url, req_headers))
        elif method == PUT:
            result = handle_general_errors(put(url, payload, req_headers))
        else:
            log.error('Unsupported request method %s', method)
            parser.print_help()
            sys.exit(1)
        try:
            log_request_info(method, log_command,
                             url, result.json(), result.status_code)
        except ValueError:
            log_request_info(method, log_command,
                             url, result.text, result.status_code)
        return result
    except requests.exceptions.SSLError as ssl_error:
        print(_(SSL_ERROR_MSG))
        log.error(ssl_error)
        if parser is not None:
            parser.print_help()
        sys.exit(1)
    except requests.exceptions.ConnectionError as conn_err:
        print(_(CONNECTION_ERROR_MSG))
        log.error(conn_err)
        if parser is not None:
            parser.print_help()
        sys.exit(1)
Beispiel #16
0
    def main(self):
        """Execute of subcommand operation.

        Method determine whether to display usage or pass input
        to find the best command match. If no match is found the
        usage is displayed
        """
        self.args = self.parser.parse_args()
        setup_logging(self.args.verbosity)
        if self.args.subcommand != server.SUBCOMMAND or \
            (self.args.subcommand == server.SUBCOMMAND and
             self.args.action != server.CONFIG):
            # Before attempting to run command, check server location
            server_location = get_server_location()
            if server_location is None or server_location == '':
                log.error(_(messages.SERVER_CONFIG_REQUIRED))
                log.error('$ qpc server config --host HOST --port PORT')
                sys.exit(1)

        if (self.args.subcommand != server.SUBCOMMAND
                and not read_client_token()):
            log.error(_(messages.SERVER_LOGIN_REQUIRED))
            log.error('$ qpc server login')
            sys.exit(1)

        if self.args.subcommand in self.subcommands:
            subcommand = self.subcommands[self.args.subcommand]
            if self.args.action in subcommand:
                action = subcommand[self.args.action]
                action.main(self.args)
            else:
                self.parser.print_help()
        else:
            self.parser.print_help()
Beispiel #17
0
def get_source_ids(parser, source_names):
    """Grab the source ids from the source if it exists.

    :returns Boolean regarding the existence of source &
    the source ids
    """
    not_found = False
    source_ids = []
    for source_name in set(source_names):
        # check for existence of source
        response = request(parser=parser,
                           method=GET,
                           path=source.SOURCE_URI,
                           params={'name': source_name},
                           payload=None)
        if response.status_code == codes.ok:  # pylint: disable=no-member
            json_data = response.json()
            count = json_data.get('count', 0)
            results = json_data.get('results', [])
            if count == 1:
                source_entry = results[0]
                source_ids.append(source_entry['id'])
            else:
                print(_(messages.SOURCE_DOES_NOT_EXIST % source_name))
                not_found = True
        else:
            print(_(messages.SOURCE_DOES_NOT_EXIST % source_name))
            not_found = True
    return not_found, source_ids
Beispiel #18
0
    def _validate_args(self):
        print(_(messages.INSIGHTS_REQUIRE_SUDO))
        CliCommand._validate_args(self)

        # Validate target report output location
        try:
            validate_write_file(self.tmp_tar_name, 'tmp_tar_name')
        except ValueError:
            print(_(messages.INSIGHTS_TMP_ERROR % self.tmp_tar_name))
            sys.exit(1)

        # Validate Insights client
        if self.args.no_gpg:
            self.insights_command = InsightsCommands(no_gpg=True)
        else:
            self.insights_command = InsightsCommands()
        self._check_insights_install()
        self._check_insights_version()
        print(_(messages.INSIGHTS_IS_VERIFIED))

        # obtaining the report as tar.gz
        if self.args.json_file:
            self._obtain_insights_report_from_local_file()
        else:
            self._obtain_insights_report_from_qpc_server()
Beispiel #19
0
 def _validate_args(self):
     self.req_headers = {'Accept': 'application/gzip'}
     try:
         validate_write_file(self.args.path, 'output-file')
     except ValueError as error:
         print(error)
         sys.exit(1)
     check_extension('tar.gz', self.args.path)
     if self.args.report_id is None:
         # Lookup scan job id
         response = request(parser=self.parser, method=GET,
                            path='%s%s' % (scan.SCAN_JOB_URI,
                                           self.args.scan_job_id),
                            payload=None)
         if response.status_code == codes.ok:  # pylint: disable=no-member
             json_data = response.json()
             self.report_id = json_data.get('report_id')
             if self.report_id:
                 self.req_path = '%s%s' % (self.req_path, self.report_id)
             else:
                 print(_(messages.DOWNLOAD_NO_REPORT_FOR_SJ %
                         self.args.scan_job_id))
                 sys.exit(1)
         else:
             print(_(messages.DOWNLOAD_SJ_DOES_NOT_EXIST %
                     self.args.scan_job_id))
             sys.exit(1)
     else:
         self.report_id = self.args.report_id
         self.req_path = '%s%s' % (self.req_path, self.report_id)
Beispiel #20
0
def get_password(args, req_payload, add_none=True):
    """Collect the password value and place in credential dictionary.

    :param args: the command line arguments
    :param req_payload: the dictionary for the request
    :param add_none: add None for a key if True vs. not in dictionary
    :returns: the updated dictionary
    """
    if 'password' in args and args.password:
        print(_(messages.CONN_PASSWORD))
        pass_prompt = getpass()
        req_payload['password'] = pass_prompt or None
    elif add_none:
        req_payload['password'] = None
    if 'ssh_passphrase' in args and args.ssh_passphrase:
        print(_(messages.SSH_PASSPHRASE))
        pass_prompt = getpass()
        req_payload['ssh_passphrase'] = pass_prompt or None
    elif add_none:
        req_payload['ssh_passphrase'] = None
    if 'become_password' in args and args.become_password:
        print(_(messages.BECOME_PASSWORD))
        pass_prompt = getpass()
        req_payload['become_password'] = pass_prompt or None
    elif add_none:
        req_payload['become_password'] = None

    return req_payload
Beispiel #21
0
 def _check_insights_version(self):
     version_command = self.insights_command.version()
     process = subprocess.Popen(version_command,
                                stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE)
     streamdata = format_subprocess_stderr(process)
     code = process.returncode
     version_check = check_insights_version(streamdata,
                                            insights.CLIENT_VERSION,
                                            insights.CORE_VERSION)
     if not version_check['results'] or code != 0:
         if 'client' in version_check.keys():
             print(_(messages.BAD_CLIENT_VERSION %
                     (version_check['client'],
                      insights.CLIENT_VERSION)))
         if 'core' in version_check.keys():
             print(_(messages.BAD_CORE_VERSION %
                     (version_check['core'],
                      insights.CORE_VERSION)))
         if 'error' in version_check.keys():
             print(_(messages.ERROR_INSIGHTS_VERSION %
                     (version_check['error'])))
         print(_(messages.CHECK_VERSION %
                 (' '.join(version_command))))
         sys.exit(1)
Beispiel #22
0
 def _handle_response_success(self):
     # pylint: disable=no-member
     if self.response.status_code in [codes.ok]:
         json_data = self.response.json()
         count = json_data.get('count', 0)
         results = json_data.get('results', [])
         if count == 0:
             # if GET is used for single scan job,
             # count doesn't exist and will be 0
             if 'id' in self.args and self.args.id:
                 data = pretty_print(json_data)
                 print(data)
             else:
                 print(_(messages.SCAN_LIST_NO_SCANS))
                 sys.exit(1)
         else:
             data = pretty_print(results)
             print(data)
         if json_data.get('next'):
             next_link = json_data.get('next')
             params = urlparse.parse_qs(urlparse.urlparse(next_link).query)
             page = params.get('page', ['1'])[0]
             if self.req_params:
                 self.req_params['page'] = page
             else:
                 self.req_params = {'page': page}
             input(_(messages.NEXT_RESULTS))
             self._do_command()
     else:
         print(_(messages.SCAN_LIST_NO_SCANS))
         sys.exit(1)
Beispiel #23
0
    def __init__(self, subparsers):
        """Create command."""
        # pylint: disable=no-member
        CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                            subparsers.add_parser(self.ACTION), GET,
                            report.REPORT_URI, [codes.ok])
        id_group = self.parser.add_mutually_exclusive_group(required=True)
        id_group.add_argument('--scan-job',
                              dest='scan_job_id',
                              metavar='SCAN_JOB_ID',
                              help=_(messages.REPORT_SCAN_JOB_ID_HELP))
        id_group.add_argument('--report',
                              dest='report_id',
                              metavar='REPORT_ID',
                              help=_(messages.REPORT_REPORT_ID_HELP))

        group = self.parser.add_mutually_exclusive_group(required=True)
        group.add_argument('--json',
                           dest='output_json',
                           action='store_true',
                           help=_(messages.REPORT_OUTPUT_JSON_HELP))
        group.add_argument('--csv',
                           dest='output_csv',
                           action='store_true',
                           help=_(messages.REPORT_OUTPUT_CSV_HELP))

        self.parser.add_argument('--output-file',
                                 dest='path',
                                 metavar='PATH',
                                 help=_(messages.REPORT_PATH_HELP),
                                 required=True)
        self.report_id = None
Beispiel #24
0
    def _validate_args(self):
        CliCommand._validate_args(self)
        if self.args.output_json:
            self.req_headers = {'Accept': 'application/json'}
        if self.args.output_csv:
            self.req_headers = {'Accept': 'text/csv'}

        try:
            validate_write_file(self.args.path, 'output-file')
        except ValueError as error:
            print(error)
            sys.exit(1)

        # Lookup scan job id
        response = request(parser=self.parser, method=GET,
                           path='%s%s' % (scan.SCAN_URI, self.args.scan_id),
                           payload=None)
        if response.status_code == codes.ok:  # pylint: disable=no-member
            json_data = response.json()
            self.fact_collection_id = json_data.get('fact_collection_id')
            if self.fact_collection_id:
                self.req_path = '%s%s' % (
                    self.req_path, self.fact_collection_id)
            else:
                print(_(messages.REPORT_NO_REPORT_FOR_SJ %
                        self.args.scan_id))
                sys.exit(1)
        else:
            print(_(messages.REPORT_SJ_DOES_NOT_EXIST %
                    self.args.scan_id))
            sys.exit(1)
Beispiel #25
0
 def __init__(self, subparsers):
     """Create command."""
     # pylint: disable=no-member
     CliCommand.__init__(self, self.SUBCOMMAND, self.ACTION,
                         subparsers.add_parser(self.ACTION), GET,
                         scan.SCAN_URI, [codes.ok])
     self.parser.add_argument(
         '--type',
         dest='type',
         choices=[scan.SCAN_TYPE_CONNECT, scan.SCAN_TYPE_INSPECT],
         metavar='TYPE',
         help=_(messages.SCAN_TYPE_FILTER_HELP),
         required=False)
     self.parser.add_argument(
         '--status',
         dest='status',
         choices=[
             scan.SCAN_STATUS_CREATED, scan.SCAN_STATUS_PENDING,
             scan.SCAN_STATUS_RUNNING, scan.SCAN_STATUS_PAUSED,
             scan.SCAN_STATUS_CANCELED, scan.SCAN_STATUS_COMPLETED,
             scan.SCAN_STATUS_FAILED
         ],
         metavar='STATUS',
         help=_(messages.SCAN_STATUS_FILTER_HELP),
         required=False)
Beispiel #26
0
    def _obtain_insights_report_from_local_file(self):
        """Load local report, validate, and write tar.gz."""
        json_file = self.args.json_file
        if not os.path.isfile(json_file):
            print(_(messages.INSIGHTS_LOCAL_REPORT_NOT % json_file))
            sys.exit(1)

        insights_report_dict = None
        with open(json_file) as insights_report_file:
            try:
                insights_report_dict = json.load(insights_report_file)
            except json_exception_class:
                print(_(messages.INSIGHTS_LOCAL_REPORT_NOT_JSON % json_file))
                sys.exit(1)

        # Validate insights report
        valid, error = self._verify_report_details(insights_report_dict)
        if not valid:
            print(_(messages.INVALID_REPORT_INSIGHTS_UPLOAD % (self.report_id, error)))
            sys.exit(1)

        insights_name = 'report_id_%s/%s.%s' % (self.report_id,
                                                'insights',
                                                'json')
        reports_dict = {}
        reports_dict[insights_name] = insights_report_dict
        tar_buffer = create_tar_buffer(reports_dict)
        # write file content to disk
        write_file(self.tmp_tar_name,
                   tar_buffer,
                   True)
Beispiel #27
0
 def _handle_response_success(self):
     json_data = self.response.json()
     count = json_data.get('count', 0)
     if self.args.name and count == 0:
         print(_(messages.CRED_NOT_FOUND % self.args.name))
         sys.exit(1)
     elif self.args.name and count == 1:
         # delete single credential
         entry = json_data.get('results')[0]
         if self._delete_entry(entry) is False:
             sys.exit(1)
     elif count == 0:
         print(_(messages.CRED_NO_CREDS_TO_REMOVE))
         sys.exit(1)
     else:
         # remove all entries
         remove_error = []
         next_link = json_data.get('next')
         results = json_data.get('results')
         for entry in results:
             if self._delete_entry(entry, print_out=False) is False:
                 remove_error.append(entry['name'])
         if remove_error != []:
             cred_err = ','.join(remove_error)
             print(_(messages.CRED_PARTIAL_REMOVE % cred_err))
             sys.exit(1)
         else:
             if not next_link:
                 print(_(messages.CRED_CLEAR_ALL_SUCCESS))
             else:
                 self._do_command()
Beispiel #28
0
 def _handle_response_success(self):
     try:
         write_file(self.args.path, self.response.content, binary=True)
         print(_(messages.REPORT_SUCCESSFULLY_WRITTEN))
     except EnvironmentError as err:
         err_msg = _(messages.WRITE_FILE_ERROR % (self.args.path, err))
         print(err_msg)
         sys.exit(1)
Beispiel #29
0
 def _validate_filename(self, top_folder, filename):
     filepath = Path(filename)
     if filepath.parent != top_folder:
         log.error(_(messages.INSIGHTS_REPORT_CONTENT_UNEXPECTED))
         raise SystemExit(1)
     if filepath.suffix != ".json":
         log.error(_(messages.INSIGHTS_REPORT_CONTENT_NOT_JSON))
         raise SystemExit(1)
Beispiel #30
0
 def _handle_response_error(self):
     if self.args.report_id is None:
         print(_(messages.REPORT_NO_SUMMARY_REPORT_FOR_SJ %
                 self.args.scan_job_id))
     else:
         print(_(messages.REPORT_NO_SUMMARY_REPORT_FOR_REPORT_ID %
                 self.args.report_id))
     sys.exit(1)