def run(self, line):
        """ Main load worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, _) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.loadvalidation(options)
        returnvalue = False

        loadcontent = dict()

        if options.mpfilename:
            sys.stdout.write("Loading configuration for multiple servers...\n")
        else:
            sys.stdout.write("Loading configuration...\n")

        for files in self.filenames:
            if not os.path.isfile(files):
                raise InvalidFileInputError("File '%s' doesn't exist. Please " \
                                "create file by running save command." % files)
            if options.encryption:
                with open(files, "rb") as myfile:
                    data = myfile.read()
                    data = Encryption().decrypt_file(data, \
                                                        options.encryption)
            else:
                with open(files, "r") as myfile:
                    data = myfile.read()

            try:
                loadcontents = json.loads(data)
            except:
                raise InvalidFileFormattingError("Invalid file formatting " \
                                                    "found in file %s" % files)

            if options.mpfilename:
                mfile = options.mpfilename
                outputdir = None

                if options.outdirectory:
                    outputdir = options.outdirectory

                if self.runmpfunc(mpfile=mfile, lfile=files, \
                                                        outputdir=outputdir):
                    return ReturnCodes.SUCCESS
                else:
                    raise MultipleServerConfigError("One or more servers "\
                                        "failed to load given configuration.")

            results = False
            validation_errs = []

            for loadcontent in loadcontents:
                for content, loaddict in loadcontent.items():
                    inputlist = list()

                    if content == "Comments":
                        continue

                    inputlist.append(content)
                    if options.biospassword:
                        inputlist.extend(
                            ["--biospassword", options.biospassword])

                    self.selobj.selectfunction(inputlist)
                    if self._rdmc.app.selector.lower() not in content.lower():
                        raise InvalidCommandLineError("Selector not found.\n")

                    try:
                        for _, items in loaddict.items():
                            try:
                                if self._rdmc.app.loadset(seldict=items, \
                                      latestschema=options.latestschema, \
                                      uniqueoverride=options.uniqueoverride):
                                    results = True
                            except LoadSkipSettingError as excp:
                                returnvalue = True
                                results = True
                            except:
                                raise
                    except redfish.ris.ValidationError as excp:
                        errs = excp.get_errors()
                        validation_errs.append({self._rdmc.app.selector: errs})
                    except:
                        raise

            try:
                if results:
                    self.comobj.commitfunction(options=options)
            except NoChangesFoundOrMadeError as excp:
                if returnvalue:
                    pass
                else:
                    raise excp

            if validation_errs:
                for validation_err in validation_errs:
                    for err_type in validation_err:
                        sys.stderr.write("Validation error(s) in type %s:\n" %
                                         err_type)
                        for err in validation_err[err_type]:
                            if isinstance(err,
                                          redfish.ris.RegistryValidationError):
                                sys.stderr.write(err.message)
                                sys.stderr.write('\n')

                                try:
                                    if err.reg:
                                        err.reg.print_help(str(err.sel))
                                        sys.stderr.write('\n')
                                except:
                                    pass
                raise redfish.ris.ValidationError(excp)

            if not results:
                raise NoDifferencesFoundError(
                    "No differences found from current configuration.")

        #Return code
        if returnvalue:
            return ReturnCodes.LOAD_SKIP_SETTING_ERROR

        return ReturnCodes.SUCCESS
Пример #2
0
    def run(self, line):
        """ Main raw patch worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        url = None
        headers = {}
        results = None

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.patchvalidation(options)

        contentsholder = None
        if len(args) == 1:
            if not os.path.isfile(args[0]):
                raise InvalidFileInputError("File '%s' doesn't exist. " \
                    "Please create file by running 'save' command." % args[0])

            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except:
                raise InvalidFileFormattingError("Input file '%s' was not " \
                                                 "format properly." % args[0])
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw patch only takes 1 argument.\n")
        else:
            raise InvalidCommandLineError("Missing raw patch file input "\
                                                                "argument.\n")

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError("Invalid format for " \
                                                            "--headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.patch_handler(contentsholder["path"], \
                  contentsholder["body"], verbose=self._rdmc.opts.verbose, \
                  url=url, sessionid=options.sessionid, headers=headers, \
                  response=returnresponse, silent=options.silent, \
                  optionalpassword=options.biospassword, \
                  service=options.service, providerheader=options.providerid, \
                  username=options.user, password=options.password)
        else:
            raise InvalidFileFormattingError("Input file '%s' was not format" \
                                                        " properly." % args[0])

        if results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(\
                                 results._http_response.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.text)

        #Return code
        return ReturnCodes.SUCCESS
Пример #3
0
    def run(self, line):
        """ Main iloaccounts function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if len(args) > 4:
            raise InvalidCommandLineError("Invalid number of parameters for "\
                                                                "this command.")

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.iloaccountsvalidation(options)

        redfish = self._rdmc.app.current_client.monolith.is_redfish
        results = self._rdmc.app.get_handler(self.typepath.defs.accountspath,\
          service=False, silent=True).dict[self.typepath.defs.collectionstring]
        path = None

        if 'Id' not in results[0].keys():
            newresults = []

            for acct in results:
                acct = self._rdmc.app.get_handler(acct[self.typepath.defs.\
                                hrefstring], service=True, silent=True).dict
                newresults.append(acct)

            results = newresults

        if not results:
            raise NoContentsFoundForOperationError("")

        outdict = dict()
        if not args:
            if not options.json:
                sys.stdout.write("iLO Account info: \n[Id]LoginName (Username): "\
                                "\nPrivileges\n-----------------\n")
            for acct in sorted(results, key=lambda k: int(k['Id'])):
                privstr = ""
                privs = acct['Oem'][self.typepath.defs.\
                                            oemhp]['Privileges']
                if 'ServiceAccount' in acct['Oem'][self.typepath.defs.oemhp].keys() and \
                acct['Oem'][self.typepath.defs.oemhp]['ServiceAccount']:
                    service = 'ServiceAccount=True'
                else:
                    service = 'ServiceAccount=False'
                if not options.json:
                    for priv in privs:
                        privstr += priv + '=' + str(privs[priv]) + '\n'
                    sys.stdout.write("[%s] %s (%s):\n%s\n%s\n" % (acct['Id'], acct['UserName'],\
                                    acct['Oem'][self.typepath.defs.\
                                                oemhp]['LoginName'], service, privstr))
                keyval = '['+str(acct['Id'])+'] '+acct['Oem'][self.typepath.\
                                                    defs.oemhp]['LoginName']
                outdict[keyval] = privs
                outdict[keyval]['ServiceAccount'] = service.split(
                    '=')[-1].lower()
            if options.json:
                sys.stdout.write(str(json.dumps(outdict, indent=2)))
                sys.stdout.write('\n')
        elif args[0].lower() == 'changepass':
            if len(args) == 2:
                sys.stdout.write('Please input the new password.\n')
                tempinput = getpass.getpass()

                if tempinput and tempinput != '\r':
                    tempinput = tempinput
                    args.extend([tempinput])
                else:
                    raise InvalidCommandLineError("Empty or invalid password" \
                                                                    " was entered.")
            if len(args) == 3:
                account = args[1]

                for acct in results:
                    if acct['Id'] == account or acct['Oem'][self.typepath.\
                                                            defs.oemhp]\
                                                    ['LoginName'] == account:
                        if redfish:
                            path = acct['@odata.id']
                            break
                        else:
                            path = acct['links']['self']['href']
                            break
                if options.encode:
                    args[2] = Encryption.decode_credentials(args[2])
                body = {'Password': args[2]}

                if path and body:
                    self._rdmc.app.patch_handler(path, body, service=True)
                else:
                    raise NoContentsFoundForOperationError('Unable to find '\
                                                'the specified account.')
            else:
                raise InvalidCommandLineError('Invalid number of parameters.')

        elif args[0].lower() == 'add':
            args.remove('add')
            if len(args) == 2:
                sys.stdout.write('Please input the account password.\n')
                tempinput = getpass.getpass()

                if tempinput and tempinput != '\r':
                    tempinput = tempinput
                    args.extend([tempinput])
                else:
                    raise InvalidCommandLineError("Empty or invalid password" \
                                                                    " was entered.")
            if not len(args) == 3:
                raise InvalidCommandLineError('Invalid number of parameters.')

            privs = self.getprivs(options)
            path = self.typepath.defs.accountspath

            if options.encode:
                args[0] = Encryption.decode_credentials(args[0])
                args[2] = Encryption.decode_credentials(args[2])

            body = {"UserName": args[0], "Password": args[2], "Oem": {self.\
                                        typepath.defs.oemhp: {"Privileges": \
                                              privs, "LoginName": args[1]}}}

            self.addvalidation(args[0], args[1], args[2], results)
            if options.serviceacc:
                body["Oem"][self.typepath.defs.oemhp].update(
                    {"ServiceAccount": True})
            if path and body:
                self._rdmc.app.post_handler(path, body)

        elif args[0].lower() == 'delete':
            args.remove('delete')

            try:
                account = args[0]
            except:
                raise InvalidCommandLineError('No item entered to delete.')

            for acct in results:
                if acct['Id'] == account or acct['Oem'][self.typepath.\
                                                    defs.oemhp]\
                                            ['LoginName'] == account:
                    if redfish:
                        path = acct['@odata.id']
                        break
                    else:
                        path = acct['links']['self']['href']
                        break

            if path:
                self._rdmc.app.delete_handler(path)
            else:
                raise NoContentsFoundForOperationError('Unable to find '\
                                            'the specified account.')
        else:
            raise InvalidCommandLineError('Invalid command.')

        return ReturnCodes.SUCCESS
Пример #4
0
    def run(self, line):
        """ Main disk inventory worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.drivesanitizevalidation(options)

        if not args and not options.all:
            raise InvalidCommandLineError(
                'You must include a physical drive to sanitize.')
        elif not options.controller:
            raise InvalidCommandLineError(
                'You must include a controller to select.')
        else:
            if len(args) > 1:
                physicaldrives = args
            elif len(args) == 1:
                physicaldrives = args[0].replace(', ', ',').split(',')
            else:
                physicaldrives = None

        self.selobj.selectfunction("SmartStorageConfig.")
        content = OrderedDict()
        for controller in self._rdmc.app.getprops():
            try:
                content[int(controller.get('Location',
                                           None).split(' ')[-1])] = controller
            except (AttributeError, KeyError):
                pass

        controldict = {}
        use_slot = False
        use_indx = False

        if not options.all:
            for _opt in options.controller:
                found = False
                for pos, control in enumerate(content):
                    if isinstance(_opt, int) and not use_slot:
                        if pos == (_opt - 1):
                            controldict[_opt] = content[control]
                            found = True
                            use_indx = True
                    elif _opt.lower() == content[control]["Location"].lower(
                    ) and not use_indx:
                        controldict[int(content[control]["Location"].split(' ')[-1])] = \
                                                                                    content[control]
                        found = True
                        use_slot = True
                    if found:
                        break

                if not found:
                    sys.stderr.write("\nController \'%s\' not found in the current inventory " \
                                     "list.\n" % _opt)
        else:
            controldict.update(content)

        if self.sanitizedrives(controldict, physicaldrives, options.all):
            if options.reboot:
                self.rebootobj.run("ColdBoot")
                sys.stdout.write('Preparing for sanitization...\n')
                self.monitorsanitization()
            else:
                sys.stdout.write(
                    'Sanitization will occur on the next system reboot.\n')
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main set password worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.setpasswordvalidation(options)

        #if not args:
        #    self.rdmc.ui.printer('Please input the current password.\n')
        #    tempoldpass = getpass.getpass()

        #   if tempoldpass and tempoldpass != '\r':
        #        tempoldpass = tempoldpass
        #    else:
        #        tempoldpass = '******'

        #    self.rdmc.ui.printer('Please input the new password.\n')
        #    tempnewpass = getpass.getpass()

        #    if tempnewpass and tempnewpass != '\r':
        #        tempnewpass = tempnewpass
        #    else:
        #        tempnewpass = '******'
        #    args.extend([tempnewpass, tempoldpass])

        #if len(args) < 2:
        #    raise InvalidCommandLineError("Please pass both new password and old password.")

        args = list()
        args.append(options.newpassword)
        args.append(options.currentpassword)
        count = 0
        for arg in args:
            if arg:
                if arg.lower() == 'none':
                    args[count] = None
                elif len(arg) > 2:
                    if ('"' in arg[0]
                            and '"' in arg[-1]) or ('\'' in arg[0]
                                                    and '\'' in arg[-1]):
                        args[count] = arg[1:-1]
                elif len(arg) == 2:
                    if (arg[0] == '"'
                            and arg[1] == '"') or (arg[0] == '\''
                                                   and arg[1] == '\''):
                        args[count] = None
            count += 1

        if options.encode:
            _args = []
            for arg in args:
                try:
                    arg = Encryption.decode_credentials(arg)
                    if isinstance(arg, bytes):
                        arg = arg.decode('utf-8')
                    _args.append(arg)
                except UnableToDecodeError:
                    _args.append(arg)
            args = _args
        if self.rdmc.app.typepath.defs.isgen10:
            bodydict = self.rdmc.app.get_handler(self.rdmc.app.typepath.defs.biospath,\
                service=True, silent=True).dict

            for item in bodydict['Actions']:
                if 'ChangePassword' in item:
                    path = bodydict['Actions'][item]['target']
                    break

            if options.poweron:
                body = {
                    "PasswordName": "User",
                    "OldPassword": args[1],
                    "NewPassword": args[0]
                }
            else:
                body = {"PasswordName": "Administrator", "OldPassword": args[1],\
                        "NewPassword": args[0]}

            self.rdmc.app.post_handler(path, body)
        else:
            if options.poweron:
                self.auxcommands['select'].run("HpBios.")
                self.auxcommands['set'].run(
                    "PowerOnPassword=%s OldPowerOnPassword=%s" %
                    (args[0], args[1]))
                self.auxcommands['commit'].run("")
            else:
                self.auxcommands['select'].run("HpBios.")
                self.auxcommands['set'].run(
                    "AdminPassword=%s OldAdminPassword=%s" %
                    (args[0], args[1]))
                self.auxcommands['commit'].run("")
                self.rdmc.ui.printer('\nThe session will now be terminated.\n'\
                    ' login again with updated credentials in order to continue.\n')
                self.auxcommands['logout'].run("")

        if options:
            if options.reboot:
                self.auxcommands['reboot'].run(options.reboot)

        self.cmdbase.logout_routine(self, options)
        return ReturnCodes.SUCCESS
Пример #6
0
    def run(self, line):
        """ Main raw get worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, _) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        url = None
        headers = {}

        self.getvalidation(options)

        if options.path.startswith('"') and options.path.endswith('"'):
            options.path = options.path[1:-1]

        if options.expand:
            options.path = options.path + '?$expand=.'

        if options.headers:
            extraheaders = options.headers.split(',')
            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    InvalidCommandLineError("Invalid format for --headers " \
                                                                    "option.")

        returnresponse = False
        if options.response or options.getheaders:
            returnresponse = True

        results = self.rdmc.app.get_handler(options.path, headers=headers,\
                silent=options.silent, service=options.service)

        if results and results.status == 200 and options.binfile:
            output = results.read

            filehndl = open(options.binfile[0], "wb")
            filehndl.write(output)
            filehndl.close()

        elif results and returnresponse:
            if options.getheaders:
                self.rdmc.ui.printer(
                    json.dumps(dict(results.getheaders())) + "\n")

            if options.response:
                self.rdmc.ui.printer(results.read)
        elif results and results.status == 200:
            if results.dict:
                if options.filename:
                    output = json.dumps(results.dict, indent=2, cls=redfish.ris.JSONEncoder, \
                                        sort_keys=True)

                    filehndl = open(options.filename[0], "w")
                    filehndl.write(output)
                    filehndl.close()

                    self.rdmc.ui.printer("Results written out to '%s'.\n" %
                                         options.filename[0])
                else:
                    if options.service:
                        self.rdmc.ui.printer("%s\n" % results.dict)
                    else:
                        self.rdmc.ui.print_out_json(results.dict)
        else:
            return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw put worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        headers = {}
        results = None

        self.putvalidation(options)

        contentsholder = None

        if len(args) == 1:
            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except Exception as excp:
                raise InvalidFileInputError("%s" % excp)
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw put only takes 1 argument.\n")
        else:
            raise InvalidCommandLineError(
                "Missing raw put file input argument.\n")

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.put_handler(contentsholder["path"], \
              contentsholder["body"], headers=headers, \
              response=returnresponse, silent=options.silent, \
              optionalpassword=options.biospassword, service=options.service)
        else:
            raise InvalidFileFormattingError("Input file '%s' was not "\
                                             "formatted properly." % args[0])

        if results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(\
                                 results.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.read)

        #Return code
        return ReturnCodes.SUCCESS
    def runmpfunc(self, mpfile=None, lfile=None, outputdir=None):
        """ Main worker function for multi file command

        :param mpfile: configuration file
        :type mpfile: string.
        :param lfile: custom file name
        :type lfile: string.
        :param outputdir: custom output directory
        :type outputdir: string.
        """
        self.logoutobj.run("")
        data = self.validatempfile(mpfile=mpfile, lfile=lfile)

        if data == False:
            return False

        processes = []
        finalreturncode = True
        outputform = '%Y-%m-%d-%H-%M-%S'

        if outputdir:
            if outputdir.endswith(('"', "'")) and \
                                                outputdir.startswith(('"', "'")):
                outputdir = outputdir[1:-1]

            if not os.path.isdir(outputdir):
                sys.stdout.write("The give output folder path does not " \
                                                                    "exist.\n")
                raise InvalidCommandLineErrorOPTS("")

            dirpath = outputdir
        else:
            dirpath = os.getcwd()

        dirname = '%s_%s' % (datetime.now().strftime(outputform), 'MSClogs')
        createdir = os.path.join(dirpath, dirname)
        os.mkdir(createdir)

        oofile = open(os.path.join(createdir, 'CompleteOutputfile.txt'), 'w+')
        sys.stdout.write('Create multiple processes to load configuration '\
                                            'concurrently to all servers...\n')

        while True:
            if not self.queue.empty():
                line = self.queue.get()
            else:
                break

            finput = '\n' + 'Output for ' + line[line.index('--url') +
                                                 1] + ': \n\n'
            urlvar = line[line.index('--url') + 1]
            listargforsubprocess = [sys.executable] + line

            if os.name is not 'nt':
                listargforsubprocess = " ".join(listargforsubprocess)

            logfile = open(os.path.join(createdir, urlvar + ".txt"), "w+")
            pinput = subprocess.Popen(listargforsubprocess, shell=True,\
                                                stdout=logfile, stderr=logfile)

            processes.append((pinput, finput, urlvar, logfile))

        for pinput, finput, urlvar, logfile in processes:
            pinput.wait()
            returncode = pinput.returncode
            finalreturncode = finalreturncode and not returncode

            logfile.close()
            logfile = open(os.path.join(createdir, urlvar + ".txt"), "r+")
            oofile.write(finput + str(logfile.read()))
            oofile.write('-x+x-' * 16)
            logfile.close()

            if returncode == 0:
                sys.stdout.write('Loading Configuration for {} : SUCCESS\n'\
                                                                .format(urlvar))
            else:
                sys.stdout.write('Loading Configuration for {} : FAILED\n'\
                                                                .format(urlvar))
                sys.stderr.write('return code : {}.\nFor more '\
                         'details please check {}.txt under {} directory.\n'\
                                        .format(returncode, urlvar, createdir))

        oofile.close()

        if finalreturncode:
            sys.stdout.write(
                'All servers have been successfully configured.\n')

        return finalreturncode
    def run(self, line):
        """ Main load worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.loadvalidation(options)
        returnValue = False

        loadcontent = dict()
        if options.mpfilename:
            sys.stdout.write("Loading configuration for multiple servers...\n")
        else:
            sys.stdout.write("Loading configuration...\n")

        for files in self.filenames:
            if not os.path.isfile(files):
                raise InvalidFileInputError("File '%s' doesn't exist. Please " \
                                "create file by running save command." % files)

            with open(files, "r") as myfile:
                data = myfile.read()

            try:
                loadcontents = json.loads(data)
            except:
                raise InvalidFileFormattingError("Invalid file formatting " \
                                                    "found in file %s" % files)

            if options.mpfilename:
                mfile = options.mpfilename
                outputdir = None

                if options.outdirectory:
                    outputdir = options.outdirectory

                if self.runmpfunc(mpfile=mfile, lfile=files, \
                                                        outputdir=outputdir):
                    return ReturnCodes.SUCCESS
                else:
                    raise MultipleServerConfigError("One or more servers "\
                                        "failed to load given configuration.")

            results = False

            for loadcontent in loadcontents:
                skip = False

                for content, loaddict in loadcontent.items():
                    inputlist = list()

                    if content == "Comments":
                        skip = True
                        break

                    inputlist.append(content)

                    self.selobj.selectfunction(inputlist)
                    if self._rdmc.app.get_selector().lower() not in \
                                                                content.lower():
                        raise InvalidCommandLineError("Selector not found.\n")

                    try:
                        for _, items in loaddict.items():
                            dicttolist = list(items.items())

                            if len(dicttolist) < 1:
                                continue

                            multilevel = [isinstance(x[1], dict) for x in \
                                                                    dicttolist]
                            indices = [
                                i for i, j in enumerate(multilevel) if j
                            ]

                            if len(indices) > 0:
                                for index in indices:
                                    changes = []
                                    self.loadmultihelper(dicttolist[index][0], \
                                                 dicttolist[index][1], changes)

                                    for change in changes:
                                        if self._rdmc.app.loadset(dicttolist=\
                                                dicttolist, newargs=change[0], val=change[0]):
                                            results = True

                                indices.sort(cmp=None, key=None, reverse=True)

                                #Test validate thoroughly
                                for index in indices:
                                    del dicttolist[index]

                            if len(dicttolist) < 1:
                                continue

                            try:
                                if self._rdmc.app.loadset(\
                                      dicttolist=dicttolist):
                                    results = True
                            except LoadSkipSettingError:
                                returnValue = True
                                results = True
                                pass
                            except Exception:
                                raise
                    except Exception:
                        raise

                if skip:
                    continue

                try:
                    if results:
                        self.comobj.commitfunction()
                except NoChangesFoundOrMadeError:
                    if returnValue:
                        pass
                    else:
                        raise

            if not results:
                raise NoDifferencesFoundError("No differences found from " \
                                                    "current configuration.")

        #Return code
        if returnValue:
            return ReturnCodes.LOAD_SKIP_SETTING_ERROR
        else:
            return ReturnCodes.SUCCESS
Пример #10
0
    def run(self, line, autotest=False):
        """ Main info worker function

        :param line: command line input
        :type line: string.
        :param autotest: flag to determine if running automatictesting
        :type autotest: bool.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.infovalidation(options)

        if args:
            for item in args:
                if self._rdmc.app.selector.lower().startswith('bios.') \
                                        and not 'attributes' in item.lower():
                    if not (item.lower() in HARDCODEDLIST
                            or '@odata' in item.lower()):
                        item = "Attributes/" + item

                outdata = self._rdmc.app.info(props=item, dumpjson=options.json, \
                                                latestschema=options.latestschema)

                if autotest:
                    return outdata
                if outdata and options.json:
                    UI().print_out_json(outdata)
                elif outdata:
                    sys.stdout.write(outdata)

                if not outdata:
                    raise InfoMissingEntriesError("There are no valid "\
                            "entries for info in the current instance.")
                else:
                    if len(args) > 1 and not item == args[-1]:
                        sys.stdout.write("\n************************************"\
                                     "**************\n")
        else:
            results = sorted(self._rdmc.app.info(props=None,\
                   ignorelist=HARDCODEDLIST, latestschema=options.latestschema))

            if results and autotest:
                return results
            elif results:
                sys.stdout.write("Info options:\n")
                for item in results:
                    sys.stdout.write("%s\n" % item)
            else:
                raise InfoMissingEntriesError('No info items '\
                        'available for this selected type. Try running with the '\
                        '--latestschema flag.')

        if options.logout:
            self.logoutobj.run("")

        #Return code
        return ReturnCodes.SUCCESS
Пример #11
0
    def run(self, line):
        """ Main disk inventory worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.drivesanitizevalidation(options)

        self.auxcommands['select'].selectfunction("SmartStorageConfig.")
        content = self.rdmc.app.getprops()

        controllers = self.auxcommands['smartarray'].controllers(
            options, single_use=True)
        if controllers:
            for controller in controllers:
                if int(controller) == int(options.controller):
                    controller_physicaldrives = self.auxcommands[
                        'smartarray'].physical_drives(options,
                                                      controllers[controller],
                                                      single_use=True)

        if not args and not options.all:
            raise InvalidCommandLineError(
                'You must include a physical drive to sanitize.')
        elif not options.controller:
            raise InvalidCommandLineError(
                'You must include a controller to select.')
        else:
            if len(args) > 1:
                physicaldrives = args
            elif len(args) == 1:
                physicaldrives = args[0].replace(', ', ',').split(',')
            else:
                physicaldrives = None

            controllist = []

        try:
            if options.controller.isdigit():
                slotlocation = self.get_location_from_id(options.controller)
                if slotlocation:
                    slotcontrol = slotlocation.lower().strip('\"').split(
                        'slot')[-1].lstrip()
                    for control in content:
                        if slotcontrol.lower() == control["Location"].lower(
                        ).split('slot')[-1].lstrip():
                            controllist.append(control)
            if not controllist:
                raise InvalidCommandLineError("")
        except InvalidCommandLineError:
            raise InvalidCommandLineError("Selected controller not found in the current inventory "\
                                          "list.")

        if self.sanitizedrives(controllist, physicaldrives,
                               controller_physicaldrives, options.mediatype,
                               options.all):
            if options.reboot:
                self.auxcommands['reboot'].run("ColdBoot")
                self.rdmc.ui.printer('Preparing for sanitization...\n')
                self.monitorsanitization()
            else:
                self.rdmc.ui.printer(
                    'Sanitization will occur on the next system reboot.\n')

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Пример #12
0
    def run(self, line):
        """ Main firmware update worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError('fwintegritycheck command takes no arguments')

        self.firmwareintegritycheckvalidation(options)
        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('fwintegritycheck command is ' \
                                                    'only available on iLO 5.')

        licenseres = self._rdmc.app.select(selector='HpeiLOLicense.')
        try:
            licenseres = licenseres[0]
        except:
            pass
        if not licenseres.dict['LicenseFeatures']['FWScan']:
            raise IloLicenseError("This command is not available with this iLO license.")

        select = self.typepath.defs.hpilofirmwareupdatetype
        results = self._rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        bodydict = results.resp.dict

        path = bodydict['Oem']['Hpe']['Actions']\
            ['#HpeiLOUpdateServiceExt.StartFirmwareIntegrityCheck']['target']

        self._rdmc.app.post_handler(path, {})

        if options.results:
            results_string = "Awaiting results of firmware integrity check..."
            sys.stdout.write(results_string)
            polling = 50
            found = False
            while polling > 0:
                if not polling % 5:
                    sys.stdout.write('.')
                get_results = self._rdmc.app.get_handler(bodydict['@odata.id'],\
                    service=True, silent=True)
                if get_results:
                    curr_time = datetime.strptime(bodydict['Oem']['Hpe']\
                                        ['CurrentTime'], "%Y-%m-%dT%H:%M:%SZ")
                    scan_time = datetime.strptime(get_results.dict['Oem']['Hpe']\
                        ['FirmwareIntegrity']['LastScanTime'], "%Y-%m-%dT%H:%M:%SZ")

                    if scan_time > curr_time:
                        sys.stdout.write('\nScan Result: %s\n' % get_results.dict\
                            ['Oem']['Hpe']['FirmwareIntegrity']['LastScanResult'])
                        found = True
                        break

                    polling -= 1
                    time.sleep(1)
            if not found:
                sys.stdout.write('\nPolling timed out before scan completed.\n')
                TimeOutError("")

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw patch worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        url = None
        headers = {}
        results = None

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.postvalidation(options)

        contentsholder = None

        if len(args) == 1:
            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except Exception as excp:
                raise InvalidFileInputError("%s" % excp)
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw post only takes 1 argument.\n")
        else:
            raise InvalidCommandLineError(
                "Missing raw post file input argument.\n")
        if options.encode:
            if "body" in contentsholder and "UserName" in contentsholder["body"] and \
                        "Password" in contentsholder["body"] and \
                        len(list(contentsholder["body"].keys())) == 2:
                encobj = Encryption()
                contentsholder["body"]["UserName"] = encobj.decode_credentials(\
                                            contentsholder["body"]["UserName"])
                contentsholder["body"]["Password"] = encobj.decode_credentials(\
                                            contentsholder["body"]["Password"])

        if options.headers:
            extraheaders = options.headers.split(',')
            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.post_handler(contentsholder["path"], \
                  contentsholder["body"], verbose=self._rdmc.opts.verbose, \
                  sessionid=options.sessionid, url=url, headers=headers, \
                  response=returnresponse, silent=options.silent, \
                  providerheader=options.providerid, service=options.service, \
                  username=options.user, password=options.password, \
                  is_redfish=self._rdmc.opts.is_redfish)
        else:
            raise InvalidFileFormattingError("Input file '%s' was not "\
                                             "formatted properly." % args[0])

        if results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(results.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.ori + "\n")

        #Return code
        return ReturnCodes.SUCCESS
Пример #14
0
    def setfunction(self, line, skipprint=False):
        """ Main set worker function

        :param line: command line input
        :type line: string.
        :param skipprint: boolean to determine output
        :type skipprint: boolean.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if not self._rdmc.interactive and \
                                        not self._rdmc.app.config.get_cache():
            raise InvalidCommandLineError("The 'set' command is not useful in "\
                                      "non-interactive and non-cache modes.")

        self.setvalidation(options)

        if len(args) > 0:

            for arg in args:
                if arg[0] == '"' and arg[-1] == '"':
                    arg = arg[1:-1]
                try:
                    (sel, val) = arg.split('=')
                    sel = sel.strip()
                    val = val.strip()

                    if val.lower() == "true" or val.lower() == "false":
                        val = val.lower() in ("yes", "true", "t", "1")
                except:
                    raise InvalidCommandLineError("Invalid set parameter " \
                                                  "format. [Key]=[Value]")

                newargs = list()
                if "/" in sel and not "/" in str(val):
                    newargs = arg.split("/")
                elif "/" in sel:
                    items = arg.split('=', 1)
                    newargs = items[0].split('/')
                    newargs[-1] = newargs[-1] + '=' + items[-1]
                    arg = newargs[-1]

                if not isinstance(val, bool):
                    if val:
                        if val[0] == "[" and val[-1] == "]":
                            val = val[1:-1].split(',')

                if not newargs:
                    contents = self._rdmc.app.loadset(selector=sel, val=val)
                else:
                    contents = self._rdmc.app.loadset(val=val,\
                        newargs=newargs)

                if contents == "No entries found":
                    raise InvalidOrNothingChangedSettingsError("No " \
                                   "entries found in the current " \
                                   "selection for the setting '%s'." % sel)
                elif contents == "reverting":
                    sys.stdout.write("Removing previous patch and "\
                                     "returning to the original value.\n")
                else:
                    for content in contents:
                        if self._rdmc.opts.verbose:
                            sys.stdout.write("Added the following" \
                                                                " patch:\n")
                            UI().print_out_json(content)

            if options.commit:
                self.comobj.commitfunction()

            if options.logout:
                self.logoutobj.logoutfunction("")

        else:
            raise InvalidCommandLineError("Missing parameters "\
                    "for 'set' command.\n")
Пример #15
0
    def run(self, line):
        """ Main DisableIloFunctionalityCommand function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError("disableilofunctionality command " \
                                                        "takes no arguments.")

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.ilofunctionalityvalidation(options)

        self.selobj.selectfunction("Chassis.")
        chassistype = self.getobj.getworkerfunction("ChassisType", options, \
         "ChassisType", results=True, uselist=True)

        if chassistype['ChassisType'].lower() == 'blade':
            raise IncompatableServerTypeError("disableilofunctionality command"\
                                    " is not available on blade server types.")

        select = 'Manager.'
        results = self._rdmc.app.filter(select, None, None)

        try:
            results = results[0]
        except:
            pass

        if results:
            path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("Manager. not found.")

        bodydict = results.resp.dict['Oem'][self.typepath.defs.oemhp]

        try:
            for item in bodydict['Actions']:
                if 'iLOFunctionality' in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = "iLOFunctionality"

                    path = bodydict['Actions'][item]['target']
                    body = {"Action": action}
                    break
        except:
            body = {"Action": "iLOFunctionality", \
                                "Target": "/Oem/Hp"}

        sys.stdout.write(u"Disabling iLO functionality. iLO will be unavailable"\
                         " on the logged in server until it is re-enabled "\
                         "manually.\n")

        results = self._rdmc.app.post_handler(path, body, silent=True, service=True, \
                                    response=True)

        if results.status == 200:
            sys.stdout.write(u"[%d] The operation completed " \
                                            "successfully.\n" % results.status)
        else:
            sys.stdout.write(u"[%d] No message returned by iLO.\n" %
                             results.status)

        return ReturnCodes.SUCCESS
Пример #16
0
    def run(self, line):
        """ Main disk inventory worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.frcontrollervalidation(options)

        self.selobj.selectfunction("SmartStorageConfig.")
        content = OrderedDict()
        for controller in self._rdmc.app.getprops():
            try:
                content[int(controller.get('Location',
                                           None).split(' ')[-1])] = controller
            except (AttributeError, KeyError):
                pass

        controldict = {}
        use_slot = False
        use_indx = False

        for _opt in options.controller:
            found = False
            for pos, control in enumerate(content):
                if isinstance(_opt, int) and not use_slot:
                    if pos == (_opt - 1):
                        controldict[_opt] = content[control]
                        found = True
                        use_indx = True
                elif _opt.lower() == content[control]["Location"].lower(
                ) and not use_indx:
                    controldict[int(content[control]["Location"].split(' ')[-1])] = \
                                                                                content[control]
                    found = True
                    use_slot = True
                if found:
                    break

            if not found:
                sys.stderr.write("\nController \'%s\' not found in the current inventory " \
                                 "list.\n" % _opt)

        if options.all:
            controldict.update(content)

        if not options.force:
            while True:
                if options.all:
                    ans = input("Are you sure you would like to factory reset all available " \
                                "smart array controllers? (y/n)\n")
                else:
                    ans = input("Are you sure you would like to factory reset controller(s): " \
                                "\'%s\' ? (y/n)\n" % controldict.keys())
                if ans.lower() == 'y':
                    break
                elif ans.lower() == 'n':
                    sys.stdout.write(
                        "Aborting factory reset of controllers.\n")
                    return None

        for indx, controller in enumerate(controldict):
            self._rdmc.app.patch_handler(controldict[controller]["@odata.id"], \
                                         {"Actions": [{"Action": "FactoryReset"}], \
                                          "DataGuard": "Disabled"})

            sys.stdout.write("[%d]: %s - has been reset to factory defaults.\n" % (indx + 1, \
                                                              controldict[controller]["Location"]))

        #Return code
        return ReturnCodes.SUCCESS
Пример #17
0
    def run(self, line, testing=False):
        """ Main iLO clone function

        :param line: string of arguments passed in
        :type line: str.
        :param testing: flag for automatic testing
        :type testing: bool
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.clonevalidation(options)

        isredfish = self._rdmc.app.current_client.monolith.is_redfish
        hrefstring = self._rdmc.app.current_client.monolith._hrefstring
        typestring = self._rdmc.app.current_client.monolith._typestring

        if not self.typepath.flagiften:
            raise IncompatibleiLOVersionError("iloclone command is only " \
                                                "available on iLO5 systems.")

        if len(args) == 2:
            myfile = args[1]
        else:
            myfile = options.filename

        if 'save' in args:
            clone = self.gather_clone_items(isredfish, hrefstring, typestring, \
                                                    options, testing=testing)
            self.save_clone(clone, myfile, options)
        elif 'load' in args:
            del args[args.index('load')]

            while True:
                if not testing:
                    ans = raw_input("Are you sure you would like to continue? "\
                                "All user settings will be erased. (y/n)")
                else:
                    break

                if ans.lower() == 'y':
                    break
                elif ans.lower() == 'n':
                    sys.stdout.write("Stopping command without resetting to "\
                                     "factory default settings.\n")
                    return ReturnCodes.SUCCESS

            self.apply_clone(myfile, options, testing=testing)
        else:
            raise InvalidCommandLineError("Please use save argument for saving"\
                                          " a clone file or load argument for "\
                                          "loading a clone file onto a server.")

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main onebuttonerase function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError(
                "onebuttonerase command takes no arguments.")

        self.onebuttonerasevalidation(options)

        select = "ComputerSystem."
        results = self._rdmc.app.select(selector=select)

        if self._rdmc.app.getiloversion() < 5.140:
            raise IncompatibleiLOVersionError('One Button Erase is only available on iLO 5 1.40 '\
                                                                                    'and greater.')
        try:
            results = results[0].dict
        except:
            raise NoContentsFoundForOperationError("Unable to find %s" %
                                                   select)

        if results['Oem']['Hpe']['SystemROMAndiLOEraseStatus'] == 'Idle' and \
                            results['Oem']['Hpe']['UserDataEraseStatus'] == 'Idle':

            post_path = None
            body_dict = {"SystemROMAndiLOErase": True, "UserDataErase": True}
            for item in results['Oem']['Hpe']['Actions']:
                if 'SecureSystemErase' in item:
                    post_path = results['Oem']['Hpe']['Actions'][item][
                        'target']
                    break

            if options.confirm:
                userresp = 'erase'
            else:
                userresp = input('Please type "erase" to begin erase process. Any other input will'\
                  ' cancel the operation. If you wish to skip this prompt add the --confirm flag: ')

            if userresp == 'erase':
                if post_path and body_dict:
                    self._rdmc.app.post_handler(post_path, body_dict)
                    self._rdmc.app.post_handler(results['Actions']['#ComputerSystem.Reset']\
                                                ['target'], {"Action": "ComputerSystem.Reset", \
                                                                    "ResetType": "ForceRestart"})
                    self.monitor_erase(results['@odata.id'])
                    return ReturnCodes.SUCCESS
                else:
                    NoContentsFoundForOperationError(
                        "Unable to start One Button Erase.")
            else:
                sys.stdout.write("Canceling One Button Erase.\n")
                return ReturnCodes.SUCCESS
        else:
            sys.stdout.write(
                "System is already undergoing a One Button Erase process...\n")
        if not options.nomonitor:
            self.monitor_erase(results['@odata.id'])

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main ilo reset worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.iloresetvalidation(options)

        sys.stdout.write(u'\nAfter iLO resets the session will be terminated.' \
                         '\nPlease wait for iLO to initialize completely ' \
                         'before logging in again.\n')
        sys.stdout.write(u'This process may take up to 3 minutes.\n\n')

        select = "Manager."
        results = self._rdmc.app.filter(select, None, None)

        try:
            results = results[0]
        except:
            pass

        if results:
            put_path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" % select)

        bodydict = results.resp.dict

        try:
            for item in bodydict['Actions']:
                if 'Reset' in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = 'Reset'

                    put_path = bodydict['Actions'][item]['target']
                    break
        except:
            action = "Reset"

        body = {"Action": action}

        postres = self._rdmc.app.post_handler(put_path, body, silent=True, \
                                                    service=True, response=True)
        if postres.status == 200:
            sys.stdout.write("A management processor reset is in progress.\n")
        else:
            sys.stderr.write("An error occured during iLO reset.\n")
            raise IloResponseError("")
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main SingleSignOnCommand function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if not len(args) == 2:
            raise InvalidCommandLineError(
                "singlsignon command only takes 2 parameters.")

        self.singlesignonvalidation(options)

        actionitem = None
        select = self.typepath.defs.hpilossotype
        results = self._rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("%s not found." % select)

        bodydict = results.resp.dict

        if args[0].lower() == 'importdns':
            actionitem = "ImportDNSName"
            body = {"Action": actionitem, "DNSName": args[1]}
        elif args[0].lower() == 'importcert':
            cert = None
            certtype = None
            actionitem = "ImportCertificate"

            try:
                cert = open(args[1], 'r')

                if cert:
                    certtext = cert.read()
                    cert.close()

                if certtext:
                    certtype = "DirectImportCert"
            except:
                pass

            if not certtype:
                certtype = "ImportCertUri"
                certtext = args[1]

            body = {
                "Action": actionitem,
                "CertType": certtype,
                "CertInput": certtext
            }

        elif args[0].lower() == 'deleterecord':
            if args[1].lower() == 'all':
                actionitem = "DeleteAllSSORecords"
                body = {"Action": actionitem}
            else:
                actionitem = "DeleteSSORecordbyNumber"

                try:
                    body = {"Action": actionitem, "RecordNumber": int(args[1])}
                except:
                    raise InvalidCommandLineError(
                        "Record to delete must be a number")
        else:
            raise InvalidCommandLineError('%s is not a valid command.' %
                                          args[0])

        try:
            for item in bodydict['Actions']:
                if actionitem in item:
                    if self.typepath.defs.isgen10:
                        actionitem = item.split('#')[-1]
                        body["Action"] = actionitem

                    path = bodydict['Actions'][item]['target']
                    break
        except:
            pass

        self._rdmc.app.post_handler(path, body)

        return ReturnCodes.SUCCESS
Пример #21
0
    def run(self, line):
        """ Main DisableIloFunctionalityCommand function

        :param line: string of arguments passed in
        :type line: str.
        """

        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError(
                "disableilofunctionality command takes no arguments.")

        self.ilofunctionalityvalidation(options)

        select = 'Manager.'
        results = self._rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("Manager. not found.")

        bodydict = results.resp.dict['Oem'][self.typepath.defs.oemhp]
        if bodydict['iLOFunctionalityRequired']:
            raise IncompatableServerTypeError("disableilofunctionality"\
                " command is not available. iLO functionality is required"\
                " and can not be disabled on this platform.")

        try:
            for item in bodydict['Actions']:
                if 'iLOFunctionality' in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = "iLOFunctionality"

                    path = bodydict['Actions'][item]['target']
                    body = {"Action": action}
                    break
        except:
            body = {"Action": "iLOFunctionality", \
                                "Target": "/Oem/Hp"}

        if self.ilodisablechecks(options):

            sys.stdout.write("Disabling iLO functionality. iLO will be "\
                             "unavailable on the logged in server until it is "\
                             "re-enabled manually.\n")

            results = self._rdmc.app.post_handler(path,
                                                  body,
                                                  silent=True,
                                                  service=True)

            if results.status == 200:
                sys.stdout.write(
                    "[%d] The operation completed successfully.\n" %
                    results.status)
            else:
                sys.stdout.write(
                    "[%d] iLO responded with the following info: \n" %
                    results.status)
                json_payload = json.loads(results._http_response.data)
                try:
                    sys.stdout.write("%s" % json_payload['error']\
                                     ['@Message.ExtendedInfo'][0]['MessageId'])
                except:
                    sys.stdout.write("An invalid or incomplete response was"\
                                     " received: %s\n" % json_payload)

        else:
            sys.stdout.write("iLO is currently performing a critical task and "\
                             "can not be safely disabled at this time. Please try again later.\n")

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Пример #22
0
    def setfunction(self, line, skipprint=False):
        """ Main set worker function

        :param line: command line input
        :type line: string.
        :param skipprint: boolean to determine output
        :type skipprint: boolean.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if not self._rdmc.interactive and not self._rdmc.app.config.get_cache(
        ):
            raise InvalidCommandLineError("The 'set' command is not useful in "\
                                      "non-interactive and non-cache modes.")

        self.setvalidation(options)
        fsel = None
        fval = None
        if args:

            if options.filter:
                try:
                    (fsel,
                     fval) = str(options.filter).strip('\'\" ').split('=')
                    (fsel, fval) = (fsel.strip(), fval.strip())
                except:
                    raise InvalidCommandLineError("Invalid filter" \
                      " parameter format [filter_attribute]=[filter_value]")

            if any([s.lower().startswith('adminpassword='******'oldadminpassword='******'OldAdminPassword' must also " \
                            "be set with the current password \nwhen " \
                            "changing 'AdminPassword' for security reasons.")

            for arg in args:
                if arg[0] == '"' and arg[-1] == '"':
                    arg = arg[1:-1]

                if self._rdmc.app.get_selector().lower().startswith('bios.'):
                    if 'attributes' not in arg.lower():
                        arg = "Attributes/" + arg

                try:
                    (sel, val) = arg.split('=')
                    sel = sel.strip().lower()
                    val = val.strip('"\'')

                    if val.lower() == "true" or val.lower() == "false":
                        val = val.lower() in ("yes", "true", "t", "1")
                except:
                    raise InvalidCommandLineError(
                        "Invalid set parameter format. [Key]=[Value]")

                newargs = list()

                if "/" in sel and "/" not in str(val):
                    newargs = sel.split("/")
                elif "/" in sel:
                    items = arg.split('=', 1)
                    newargs = items[0].split('/')

                if not isinstance(val, bool):
                    if val:
                        if val[0] == "[" and val[-1] == "]":
                            val = val[1:-1].split(',')

                payload = {newargs[-1]: val} if newargs else {sel: val}
                if newargs:
                    for key in newargs[:-1][::-1]:
                        payload = {key: payload}

                try:
                    contents = self._rdmc.app.loadset(seldict=payload,\
                        latestschema=options.latestschema, fltrvals=(fsel, fval), \
                                        uniqueoverride=options.uniqueoverride)
                    if not contents:
                        if not sel.lower() == 'oldadminpassword':
                            raise InvalidOrNothingChangedSettingsError("Setting " \
                                                "for '%s' is the same as " \
                                                "the current value." % sel)
                    elif contents == "No entries found":
                        raise InvalidOrNothingChangedSettingsError("No " \
                                       "entries found in the current " \
                                       "selection for the setting '%s'." % sel)
                    elif contents == "reverting":
                        sys.stdout.write("Removing previous patch and "\
                                         "returning to the original value.\n")
                    else:
                        for content in contents:
                            if self._rdmc.opts.verbose:
                                sys.stdout.write(
                                    "Added the following patch:\n")
                                UI().print_out_json(content)

                except redfish.ris.ValidationError as excp:
                    errs = excp.get_errors()

                    for err in errs:
                        if err.sel and err.sel.lower() == 'adminpassword':
                            types = self._rdmc.app.current_client.monolith.types

                            for item in types:
                                for instance in types[item]["Instances"]:
                                    if 'hpbios.' in instance.maj_type.lower():
                                        _ = [instance.patches.remove(patch) for \
                                         patch in instance.patches if \
                                         patch.patch[0]['path'] == '/OldAdminPassword']

                        if isinstance(err,
                                      redfish.ris.RegistryValidationError):
                            sys.stderr.write(err.message)
                            sys.stderr.write('\n')

                            if err.reg and not skipprint:
                                err.reg.print_help(sel)
                                sys.stderr.write('\n')

                    raise redfish.ris.ValidationError(excp)

            if options.commit:
                self.comobj.commitfunction(options)

            if options.reboot and not options.commit:
                self.rebootobj.run(options.reboot)

            if options.logout:
                self.logoutobj.run("")

        else:
            raise InvalidCommandLineError(
                "Missing parameters for 'set' command.\n")
    def run(self, line):
        """ Main reboot worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if len(args) < 2:
            self.rebootvalidation(options)
        else:
            raise InvalidCommandLineError("Invalid number of parameters." \
                                      " Reboot takes a maximum of 1 parameter.")

        if not args:
            sys.stdout.write('\nAfter the server is rebooted the session' \
             ' will be terminated.\nPlease wait for the server' \
             ' to boot completely to login again.\n')
            sys.stdout.write('Rebooting server in 3 seconds...\n')
            time.sleep(3)
        else:
            self.printreboothelp(args[0])

        select = "ComputerSystem."
        results = self._rdmc.app.select(selector=select)
        oemlist = ['press', 'pressandhold', 'coldboot']

        try:
            results = results[0]
        except:
            pass

        if results:
            put_path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" % select)

        if args and args[0].lower() in oemlist:
            bodydict = results.resp.dict['Oem'][self.typepath.defs.oemhp]

            if args[0].lower() == 'coldboot':
                resettype = 'SystemReset'
            else:
                resettype = 'PowerButton'
        else:
            bodydict = results.resp.dict
            resettype = 'Reset'

        try:
            for item in bodydict['Actions']:
                if resettype in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = resettype

                    put_path = bodydict['Actions'][item]['target']
                    break
        except:
            action = resettype

        if args and not args[0].lower() == "forcerestart":
            if args[0].lower() == "on":
                body = {"Action": action, "ResetType": "On"}
            elif args[0].lower() == "forceoff":
                body = {"Action": action, "ResetType": "ForceOff"}
            elif args[0].lower() == "nmi":
                body = {"Action": action, "ResetType": "Nmi"}
            elif args[0].lower() == "pushpowerbutton":
                body = {"Action": action, "ResetType": "PushPowerButton"}
            elif args[0].lower() == "press":
                body = {"Action": action, "PushType": "Press"}
            elif args[0].lower() == "pressandhold":
                body = {"Action": action, "PushType": "PressAndHold"}
            elif args[0].lower() == "coldboot":
                body = {"Action": action, "ResetType": "ColdBoot"}
        else:
            body = {"Action": action, "ResetType": "ForceRestart"}

        if options.confirm is True:
            count = 0
            while True:
                count = count+1
                confirmation = input("Rebooting system, type yes to confirm or no to abort:")
                if confirmation.lower() in ('no', 'n') or count > 3:
                    sys.stdout.write('Aborting reboot.\n')
                    return ReturnCodes.SUCCESS
                elif confirmation.lower() in ('yes', 'y'):
                    break

        self._rdmc.app.post_handler(put_path, body)

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main disk inventory worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, _) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.createlogicaldrivevalidation(options)

        if options.controller:
            controllers = self.auxcommands['smartarray'].controllers(
                options, single_use=True)
            try:
                controller = controllers[next(iter(controllers))]
                (create_flag,
                 newdrive) = self.createlogicaldrive(options, controller)
                if create_flag:
                    #if controller.get("DataGuard"):
                    #    controller["DataGuard"] = "Disabled"
                    temp_odata = controller['@odata.id']
                    #temp_l = controller['LogicalDrives']
                    #temp_p = controller['PhysicalDrives']
                    #readonly_removed = self.rdmc.app.removereadonlyprops(controller)
                    payload_dict = dict()
                    payload_dict['DataGuard'] = "Disabled"
                    #readonly_removed['LogicalDrives'] = controller['LogicalDrives']
                    #readonly_removed['PhysicalDrives'] = temp_p
                    if not 'settings' in temp_odata:
                        temp_odata = temp_odata + "settings/"
                    settings_controller = self.rdmc.app.get_handler(temp_odata, \
                                                            service=False, silent=True)
                    # Fix for multiple logical creation at single reboot
                    if self.rdmc.app.typepath.defs.isgen9:
                        payload_dict['logical_drives'] = dict()
                        payload_dict['logical_drives']['new'] = newdrive
                    else:
                        payload_dict[
                            'LogicalDrives'] = settings_controller.dict[
                                'LogicalDrives']
                        payload_dict['LogicalDrives'].append(newdrive)
                    self.rdmc.ui.printer(
                        "CreateLogicalDrive path and payload: %s, %s\n" %
                        (temp_odata, payload_dict))
                    self.rdmc.app.put_handler(temp_odata, payload_dict, \
                                    headers={'If-Match': self.getetag(temp_odata)})
                    self.rdmc.app.download_path([temp_odata], path_refresh=True, \
                                                                                    crawl=False)
            except Exception as excp:
                raise InvalidCommandLineError("%s for  "\
                            "controller ID ('--controller=%s')"% (str(excp), options.controller))

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw patch worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, _) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        headers = {}
        results = []

        self.patchvalidation(options)

        contentsholder = None
        try:
            with open(options.path, 'r') as _if:
                contentsholder = json.loads(_if.read(),
                                            object_pairs_hook=OrderedDict)
        except IOError:
            raise InvalidFileInputError("File '%s' doesn't exist. " \
                                "Please create file by running 'save' command." % options.path)
        except (ValueError):
            raise InvalidFileFormattingError("Input file '%s' was not " \
                                                            "formatted properly." % options.path)

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            results.append(self._rdmc.app.patch_handler(contentsholder["path"], \
                  contentsholder["body"], headers=headers, silent=options.silent, \
                  optionalpassword=options.biospassword, service=options.service))

        elif all([re.match("^\/(\S+\/?)+$", key) for key in contentsholder]):
            for path, body in contentsholder.items():
                results.append(self._rdmc.app.patch_handler(path, \
                                body, headers=headers, silent=options.silent, \
                                optionalpassword=options.biospassword, service=options.service))

        else:
            raise InvalidFileFormattingError("Input file '%s' was not format properly." % \
                                                                                    options.path)

        returnresponse = False

        if options.response or options.getheaders:
            returnresponse = True

        if results and returnresponse:
            for result in results:
                if options.getheaders:
                    sys.stdout.write(
                        json.dumps(dict(result.getheaders())) + "\n")

                if options.response:
                    sys.stdout.write(result.read)
                    sys.stdout.write("\n")

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Пример #26
0
    def run(self, line):
        """ Main SentTestCommand function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if not len(args) == 1:
            raise InvalidCommandLineError(
                "sendtest command takes only one argument.")

        body = None
        path = None
        actionitem = None

        self.sendtestvalidation(options)

        if args[0].lower() == 'snmpalert':
            select = self.rdmc.app.typepath.defs.snmpservice
            actionitem = "SendSNMPTestAlert"
        elif args[0].lower() == 'alertmail':
            select = self.rdmc.app.typepath.defs.managernetworkservicetype
            actionitem = "SendTestAlertMail"
        elif args[0].lower() == 'syslog':
            select = self.rdmc.app.typepath.defs.managernetworkservicetype
            actionitem = "SendTestSyslog"
        else:
            raise InvalidCommandLineError("sendtest command does not have " \
                                                    "parameter %s." % args[0])

        results = self.rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("%s not found.It may not " \
                                       "be available on this system." % select)

        bodydict = results.resp.dict

        try:
            if 'Actions' in bodydict:
                for item in bodydict['Actions']:
                    if actionitem in item:
                        if self.rdmc.app.typepath.defs.isgen10:
                            actionitem = item.split('#')[-1]

                        path = bodydict['Actions'][item]['target']
                        break
            else:
                for item in bodydict['Oem'][
                        self.rdmc.app.typepath.defs.oemhp]['Actions']:
                    if actionitem in item:
                        if self.rdmc.app.typepath.defs.isgen10:
                            actionitem = item.split('#')[-1]

                        path = bodydict['Oem'][self.rdmc.app.typepath.defs.oemhp][\
                                                'Actions'][item]['target']
                        break

            body = {"Action": actionitem}
        except:
            body = {"Action": actionitem, "Target": "/Oem/Hp"}

        self.rdmc.app.post_handler(path, body)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main iscsi configuration worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if len(args) > 2:
            raise InvalidCommandLineError("Invalid number of parameters. " \
                "virtualmedia command takes a maximum of 2 parameters.")
        else:
            self.virtualmediavalidation(options)

        resp = self._rdmc.app.get_handler(\
                          '/rest/v1/Managers/1/VirtualMedia/1', response=True, silent=True)

        if not resp.status == 200:
            raise IloLicenseError('')

        self.selobj.run("VirtualMedia.")
        ilover = self._rdmc.app.getiloversion()

        if self._rdmc.app.current_client.monolith.is_redfish:
            isredfish = True
            paths = self.getobj.getworkerfunction("@odata.id", options, results=True, uselist=False)
            ids = self.getobj.getworkerfunction("Id", options, results=True, uselist=False)
            paths = {ind:path for ind, path in enumerate(paths)}
            ids = {ind:id for ind, id in enumerate(ids)}
            for path in paths:
                paths[path] = paths[path]['@odata.id']
        else:
            isredfish = False
            paths = self.getobj.getworkerfunction("links/self/href", options, \
                    results=True, uselist=False)
            ids = self.getobj.getworkerfunction("Id", options, results=True, uselist=False)
            paths = {ind:path for ind, path in enumerate(paths)}
            ids = {ind:id for ind, id in enumerate(ids)}
            for path in paths:
                paths[path] = paths[path]['links']['self']['href']
        # To keep indexes consistent between versions
        if not list(ids.keys())[0] == list(list(ids.values())[0].values())[0]:
            finalpaths = {}
            for path in paths:
                finalpaths.update({int(list(ids[path].values())[0]): paths[path]})
            paths = finalpaths
        if options.removevm:
            self.vmremovehelper(args, options, paths, isredfish, ilover)
        elif len(args) == 2:
            self.vminserthelper(args, options, paths, isredfish, ilover)
        elif options.bootnextreset:
            self.vmbootnextreset(args, paths)
        elif not args:
            self.vmdefaulthelper(options, paths)
        else:
            raise InvalidCommandLineError("Invalid parameter(s). Please run"\
                                      " 'help virtualmedia' for parameters.")

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw get worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        url = None
        headers = {}

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.getvalidation(options)

        if len(args) > 1:
            raise InvalidCommandLineError("Raw get only takes 1 argument.\n")
        elif len(args) == 0:
            raise InvalidCommandLineError("Missing raw get input path.\n")

        if args[0].startswith('"') and args[0].endswith('"'):
            args[0] = args[0][1:-1]

        if options.expand:
            args[0] = args[0] + '?$expand=.'

        if options.headers:
            extraheaders = options.headers.split(',')
            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    InvalidCommandLineError("Invalid format for --headers " \
                                                                    "option.")

        returnresponse = False
        if options.response or options.getheaders:
            returnresponse = True

        results = self._rdmc.app.get_handler(args[0], \
                verbose=self._rdmc.opts.verbose, sessionid=options.sessionid, \
                url=url, headers=headers, response=returnresponse, \
                silent=options.silent)
        if results and options.binfile:
            output = results.read

            filehndl = open(options.binfile[0], "wb")
            filehndl.write(output)
            filehndl.close()

        elif results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(\
                                 results._http_response.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.text)
        elif results and results.status == 200:
            if results.dict:
                if options.filename:
                    output = json.dumps(results.dict, indent=2, \
                                                    cls=redfish.ris.JSONEncoder)

                    filehndl = open(options.filename[0], "w")
                    filehndl.write(output)
                    filehndl.close()

                    sys.stdout.write("Results written out to '%s'.\n" % \
                                                            options.filename[0])
                else:
                    UI().print_out_json(results.dict)
        else:
            return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION

        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw head worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        url = None

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.headvalidation(options)

        if len(args) > 1:
            raise InvalidCommandLineError("Raw head only takes 1 argument.\n")
        elif not args:
            raise InvalidCommandLineError("Missing raw head input path.\n")

        if args[0].startswith('"') and args[0].endswith('"'):
            args[0] = args[0][1:-1]

        results = self._rdmc.app.head_handler(args[0], \
                                              verbose=self._rdmc.opts.verbose, \
                                              sessionid=options.sessionid, \
                                              url=url, silent=options.silent, \
             service=options.service, \
                                              username=options.user, \
                                              password=options.password)

        content = None
        tempdict = dict()

        if results and results.status == 200:
            if results._http_response:
                content = results._http_response.msg.headers
            else:
                content = results._headers

            for item in content:
                if isinstance(item, dict):
                    for key, value in item.iteritems():
                        tempdict[key] = value
                else:
                    item = item.replace(": ", ":").replace("\r\n", "").\
                                                                split(":", 1)
                    tempdict[item[0]] = item[1]

            if options.filename:
                output = json.dumps(tempdict, indent=2, \
                                                    cls=redfish.ris.JSONEncoder)
                filehndl = open(options.filename[0], "w")
                filehndl.write(output)
                filehndl.close()

                sys.stdout.write(u"Results written out to '%s'.\n" % \
                                                            options.filename[0])
            else:
                if options.service:
                    sys.stdout.write("%s\n" % tempdict)
                else:
                    UI().print_out_json(tempdict)
        else:
            return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION

        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw delete worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        url = None
        headers = {}

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.deletevalidation(options)

        if len(args) > 1:
            raise InvalidCommandLineError(
                "Raw delete only takes 1 argument.\n")
        elif len(args) == 0:
            raise InvalidCommandLineError("Missing raw delete input path.\n")

        if args[0].startswith('"') and args[0].endswith('"'):
            args[0] = args[0][1:-1]

        if options.expand:
            args[0] = args[0] + '?$expand=.'

        try:
            currentsess = self._rdmc.app.current_client._rest_client.\
                                            _RestClientBase__session_location
        except:
            currentsess = None

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    InvalidCommandLineError("Invalid format for --headers " \
                                                                    "option.")

        if currentsess and (args[0] in currentsess):
            self._rdmc.app.logout()
            sys.stdout.write("Your session has been deleted.\nPlease log "\
                                        "back in if you wish to continue.\n")
        else:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.delete_handler(args[0], \
                verbose=self._rdmc.opts.verbose, sessionid=options.sessionid, \
                url=url, headers=headers, silent=options.silent)

        if returnresponse and results:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(\
                                 results._http_response.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.text)
        elif results.status == 404:
            return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION
        elif results.status != 200:
            return ReturnCodes.UI_CLI_USAGE_EXCEPTION

        #Return code
        return ReturnCodes.SUCCESS