def run(self, line):
        """ Main fwpkg 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("")

        self.fwpkgvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

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

        if self._rdmc.app.getiloversion() <= 5.120 and args[0].lower().startswith('iegen10'):
            raise IncompatibleiLOVersionError('Please upgrade to iLO 5 1.20 or '\
                       'greater to ensure correct flash of this firmware.')
        tempdir = ''
        if not args[0].endswith('.fwpkg'):
            InvalidFileInputError("Invalid file type. Please make sure the file "\
                                  "provided is a valid .fwpkg file type.")
        try:
            self.taskqueuecheck()
        except TaskQueueError as excp:
            if options.ignore:
                sys.stderr.write(str(excp)+'\n')
            else:
                raise excp
        try:
            components, tempdir, comptype = self.preparefwpkg(self, args[0])
            if comptype == 'D':
                raise InvalidFileInputError("Unable to flash this fwpkg file.")
            self.applyfwpkg(options, tempdir, components)

            if comptype == 'A':
                message = "Firmware will flash and does not require a reboot.\n"
            elif comptype == 'B':
                message = "A reboot is required for this firmware to take affect.\n"
            elif comptype == 'C':
                message = "This firmware will flash on reboot.\n"
            sys.stdout.write(message)
        finally:
            if tempdir:
                shutil.rmtree(tempdir)

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main installset 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("")

        self.loggedin = None
        self.comps = None
        self.loggedin = self.minstallsetvalidation()

        if self.loggedin and self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        sys.stdout.write("Warning: This command will run in interactive mode.\n")
        if args:
            raise InvalidCommandLineError("makeinstallset command takes no arguments.")

        self.minstallsetworker(options)

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #3
0
    def run(self, line):
        """ Main listcomp 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.listcomponentvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        comps = self._rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        if comps:
            self.printcomponents(comps, options)
        else:
            sys.stdout.write('No components found.\n')

        return ReturnCodes.SUCCESS
Beispiel #4
0
    def run(self, line):
        """ Main update task queue 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("")

        self.updatetaskqueuevalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        if options.resetqueue:
            self.resetqueue()
        elif options.cleanqueue:
            self.cleanqueue()
        elif not args:
            self.printqueue(options)
        elif args[0].lower() == 'create':
            self.createtask(args[1:], options)
        else:
            raise InvalidCommandLineError('Invalid command entered.')

        return ReturnCodes.SUCCESS
Beispiel #5
0
    def getprivs(self, options):
        """ find and return the privileges to set

        :param options: command line options
        :type options: list.
        """
        sesprivs = self.getsesprivs()
        setprivs = {}
        availableprivs = self.getsesprivs(availableprivsopts=True)

        if not 'UserConfigPriv' in sesprivs.keys():
            raise IdTokenError("The currently logged in account does not have the User Config "\
                             "privilege and cannot add or modify user accounts.")

        if options.optprivs:
            for priv in options.optprivs:
                priv = next(iter(priv.keys()))
                if priv not in availableprivs:
                    raise IncompatibleiLOVersionError("Privilege %s is not available on this "\
                                                                            "iLO version." % priv)

            if all(priv.values() for priv in options.optprivs):
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) and\
                                            'SystemRecoveryConfigPriv' not in sesprivs.keys():
                    raise IdTokenError("The currently logged in account must have The System "\
                                     "Recovery Config privilege to add the System Recovery "\
                                     "Config privilege.")
                else:
                    setprivs = {}
            for priv in options.optprivs:
                setprivs.update(priv)

        return setprivs
Beispiel #6
0
    def run(self, line):
        """ Main listcomp worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        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.listcomponentvalidation(options)

        if self.rdmc.app.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        comps = self.rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        if comps:
            self.printcomponents(comps, options)
        else:
            self.rdmc.ui.warn('No components found.\n')

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    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("")
        sys.stdout.write("WARNING: \'iloclone\' command is being deprecated and will be removed "\
                         "in a future release. Please use the \'serverclone\' command instead.\n")
        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 iLO 5 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 = 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 update task queue worker function

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

        self.updatetaskqueuevalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        if options.command.lower() == 'create':
            self.createtask(options.keywords.split(), options)
        else:
            if options.resetqueue:
                self.resetqueue()
            elif options.cleanqueue:
                self.cleanqueue()
            self.printqueue(options)

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #9
0
    def importcrlhelper(self, args):
        """ Helper function for importing CRL certificate

        :param args: list of args
        :type args: list.
        """
        if not self.typepath.flagiften:
            raise IncompatibleiLOVersionError(
                "This certificate is not available on this system.")

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

        try:
            results = results[0]
        except:
            pass

        if results:
            bodydict = results.resp.dict
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" %
                                                   select)

        for item in bodydict['Actions']:
            if 'ImportCRL' in item:
                action = item.split('#')[-1]
                path = bodydict['Actions'][item]['target']
                break

        body = {"Action": action, "ImportUri": args[1]}

        self._rdmc.app.post_handler(path, body)
Beispiel #10
0
    def run(self, line):
        """ Main sigrecompute 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(
                "Sigrecompute command takes no arguments.")

        self.sigrecomputevalidation(options)
        path = self.typepath.defs.systempath

        if self.typepath.defs.flagforrest:
            body = {"Action": "ServerSigRecompute", "Target": "/Oem/Hp"}
            self._rdmc.app.post_handler(path, body)
        else:
            raise IncompatibleiLOVersionError(
                "Sigrecompute action not available on redfish.")

        return ReturnCodes.SUCCESS
Beispiel #11
0
    def run(self, line):
        """ Main update maintenance window worker function

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

        self.maintenancewindowvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        windows = self._rdmc.app.getcollectionmembers(\
                                '/redfish/v1/UpdateService/MaintenanceWindows/')

        if options.command.lower() == 'add':
            self.addmaintenancewindow(options, windows, options.time_window)
        elif options.command.lower() == 'delete':
            self.deletemaintenancewindow(windows, options.identifier)
        else:
            self.listmainenancewindows(options, windows)

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Wrapper function for download command main 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("")

        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:
            url = None
            self.downloadcomponentvalidation(options)

        if options.sessionid and not url:
            raise InvalidCommandLineError('Url muse be included with ' \
                          'sessionid. Session is not required for local mode.')

        if not options.sessionid and self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        if len(args) > 1:
            raise InvalidCommandLineError("Download component only takes 1 " \
                                                "component path argument.\n")
        elif not args:
            raise InvalidCommandLineError("Download component missing " \
                                                            "component path.\n")

        start_time = time.time()
        ret = ReturnCodes.FAILED_TO_DOWNLOAD_COMPONENT

        sys.stdout.write("Downloading component, this may take a while...\n")

        if not url and 'blobstore' in self._rdmc.app.get_current_client()\
                                                ._rest_client.get_base_url():
            ret = self.downloadlocally(args[0], options)
        else:
            ret = self.downloadfunction(args[0], options, url)

        sys.stdout.write("%s\n" %
                         human_readable_time(time.time() - start_time))

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

        return ret
    def run(self, line):
        """ Wrapper function for upload command main function

        :param line: string of arguments passed in
        :type line: str.
        """
        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.uploadcommandvalidation(options)
        fwpkg = False
        if options.component.endswith('.fwpkg'):
            fwpkg = True
            comp, loc, ctype = self.auxcommands['flashfwpkg'].preparefwpkg(
                self, options.component)
            if ctype == 'C':
                options.component = comp[0]
            else:
                options.component = os.path.join(loc, comp[0])

        if self.rdmc.app.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        filestoupload = self._check_and_split_files(options)

        if self.componentvalidation(options, filestoupload):
            start_time = time.time()
            ret = ReturnCodes.FAILED_TO_UPLOAD_COMPONENT

            #ret = self.uploadfunction(filestoupload, options)
            if 'blobstore' in self.rdmc.app.current_client.base_url:
                ret = self.uploadlocally(filestoupload, options)
            else:
                ret = self.uploadfunction(filestoupload, options)

            if ret == ReturnCodes.SUCCESS:
                self.rdmc.ui.printer(
                    "%s\n" % human_readable_time(time.time() - start_time))

            if len(filestoupload) > 1:
                path, _ = os.path.split((filestoupload[0])[1])
                shutil.rmtree(path)
            elif fwpkg:
                if os.path.exists(loc):
                    shutil.rmtree(loc)
        else:
            ret = ReturnCodes.SUCCESS

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ret
Beispiel #14
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:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError('fwintegritycheck 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.firmwareintegritycheckvalidation(options)

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

        licenseres = self._rdmc.app.filter('HpeiLOLicense.', None, None)
        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.filter(select, None, None)

        try:
            results = results[0]
        except:
            pass

        bodydict = results.resp.dict

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

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

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Wrapper function for download command main 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("")

        repo = ['fwrepo']
        urilist = args[0].split('/')
        if repo[0] not in urilist:
            repo = ['/fwrepo/']
            repo[0] += args[0]
            args[0] = repo[0]

        self.downloadcomponentvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        if len(args) > 1:
            raise InvalidCommandLineError("Download component only takes 1 " \
                                                "component path argument.\n")
        elif not args:
            raise InvalidCommandLineError(
                "Download component missing component path.\n")

        start_time = time.time()
        ret = ReturnCodes.FAILED_TO_DOWNLOAD_COMPONENT

        sys.stdout.write("Downloading component, this may take a while...\n")

        if 'blobstore' in self._rdmc.app.current_client.base_url:
            ret = self.downloadlocally(args[0], options)
        else:
            ret = self.downloadfunction(args[0], options)

        sys.stdout.write("%s\n" %
                         human_readable_time(time.time() - start_time))

        logout_routine(self, options)
        #Return code
        return ret
Beispiel #16
0
    def run(self, line):
        """ Main deletecomp 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.deletecomponentvalidation(options)

        if self.rdmc.app.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                              'only available on iLO 5.')

        comps = self.rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        if not comps:
            self.rdmc.ui.warn('No components found to delete\n')

        elif options.deleteall:
            delopts = []

            for comp in comps:
                try:
                    if comp['Locked']:
                        self.rdmc.ui.warn("Unable to delete %s. It is in use by "\
                                          "an install set or update task.\n" % comp['Filename'])
                        continue
                except KeyError:
                    pass
                delopts.append(comp['@odata.id'])

            self.deletecomponents(comps, delopts)
        elif args:
            self.deletecomponents(comps, args)
        else:
            InvalidCommandLineError(
                "Please include the component(s) you wish to delete")

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #17
0
    def run(self, line):
        """ Main listcomp 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 options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.installsetvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        if args and args[0] in ['delete', 'invoke'] and not options.name:
            raise InvalidCommandLineError('Name option is required for ' \
                                          'delete and invoke commands.')
        if options.name:
            if options.name.startswith('"') and options.name.endswith('"'):
                options.name = options.name[1:-1]
        if options.removeall:
            self.removeinstallsets()
        elif not args:
            self.printinstallsets(options)
        elif args[0].lower() == 'add':
            if not len(args) == 2:
                raise InvalidCommandLineError('add command requires an ' \
                                                            'install set file.')
            else:
                self.addinstallset(args[1], options.name)
        elif args[0].lower() == 'delete':
            self.deleteinstallset(options.name)
        elif args[0].lower() == 'invoke':
            self.invokeinstallset(options)
        else:
            raise InvalidCommandLineError('%s is not a valid command.' %
                                          args[0])

        return ReturnCodes.SUCCESS
Beispiel #18
0
    def run(self, line):
        """ Main update maintenance window 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 options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.maintenancewindowvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        windows = self._rdmc.app.getcollectionmembers(\
                                '/redfish/v1/UpdateService/MaintenanceWindows/')
        if not args:
            self.listmainenancewindows(options, windows)
        elif args[0].lower() == 'add':
            if not len(args) == 2:
                raise InvalidCommandLineError("Adding a maintenance window only "\
                                              "requires one argument.")
            else:
                self.addmaintenancewindow(options, windows, args[1])
        elif args[0].lower() == 'delete':
            if not len(args) == 2:
                raise InvalidCommandLineError("Deleting a maintenance window only"\
                                              " requires one argument.")
            else:
                self.deletemaintenancewindow(windows, args[1])
        else:
            raise InvalidCommandLineError('Invalid command entered.')

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main deletecomp 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 options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.deletecomponentvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                              'only available on iLO 5.')

        comps = self._rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        if not comps:
            sys.stdout.write('No components found to delete\n')

        elif options.deleteall:
            delopts = []

            for comp in comps:
                delopts.append(comp['@odata.id'])

            self.deletecomponents(comps, delopts)
        elif args:
            self.deletecomponents(comps, args[0])
        else:
            InvalidCommandLineError("Please include the component(s) you wish "\
                                                                    "to delete")

        return ReturnCodes.SUCCESS
Beispiel #20
0
    def importcahelper(self, args):
        """ Helper function for importing TLS certificate

        :param args: list of args
        :type args: list.
        """
        if not self.typepath.flagiften:
            raise IncompatibleiLOVersionError(
                "This certificate is not available on this system.")

        tlsfile = args[1]

        try:
            with open(tlsfile) as certfile:
                certdata = certfile.read()
                certfile.close()
        except:
            raise InvalidFileInputError("Error loading the specified file.")

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

        try:
            results = results[0]
        except:
            pass

        if results:
            bodydict = results.resp.dict
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" %
                                                   select)

        for item in bodydict['Actions']:
            if 'ImportCACertificate' in item:
                action = item.split('#')[-1]
                path = bodydict['Actions'][item]['target']
                break

        body = {"Action": action, "Certificate": certdata}

        self._rdmc.app.post_handler(path, body)
    def run(self, line):
        """ Wrapper function for download command main 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.downloadcomponentvalidation(options)

        if self.rdmc.app.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                            'only available on iLO 5.')

        start_time = time.time()
        ret = ReturnCodes.FAILED_TO_DOWNLOAD_COMPONENT

        self.rdmc.ui.printer(
            "Downloading component, this may take a while...\n")

        if 'blobstore' in self.rdmc.app.current_client.base_url:
            ret = self.downloadlocally(options)
        else:
            ret = self.downloadfunction(options)

        self.rdmc.ui.printer("%s\n" %
                             human_readable_time(time.time() - start_time))

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ret
    def run(self, line):
        """Main directory 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("")

        self.directoryvalidation(options)
        if self._rdmc.app.getiloversion() < 5.140:
            raise IncompatibleiLOVersionError("Directory settings are only available on "\
                                                                        "iLO 5 1.40 or greater.")
        if len(args) < 1 or len(args) > 3:
            raise InvalidCommandLineError("Invalid number of arguments entered.")
        elif len(args) == 3 and args[0].lower() == 'kerberos':
            raise InvalidCommandLineError("Username and password can only be set for LDAP.")
        elif len(args) == 2 and args[0].lower() in ['ldap']:
            sys.stdout.write('Please input the password for the directory.\n')
            tempinput = getpass.getpass()
            args.extend([tempinput])

        elif len(args) == 2 and args[0].lower() == 'test':
            if not args[1] in ['start', 'stop', 'viewresults']:
                raise InvalidCommandLineError('Please input "start" to start the directory test, '\
                        '"stop" to stop the directory test, or "viewresults" to see the results of'\
                        ' the last directory test.')

        results = None

        if args[0].lower() == 'ldap':
            if options.realm or options.keytab:
                raise InvalidCommandLineError("Keytab and Realm options are not available for "\
                                              "LDAP.")
            try:
                results = self._rdmc.app.select(selector='AccountService.', rel=True)[0].dict
                path = results[self._rdmc.app.typepath.defs.hrefstring]
                oem = results['Oem'][self.typepath.defs.oemhp]
                local_auth = results['LocalAccountAuth']
                results = results['LDAP']
                name = 'LDAP'
            except (KeyError, IndexError):
                raise NoContentsFoundForOperationError("Unable to gather LDAP settings.")

        elif args[0].lower() == 'kerberos':
            if options.authmode or options.search:
                raise InvalidCommandLineError("Authentication and add/remove search options "\
                                              "are not available for Kerberos.")
            try:
                results = self._rdmc.app.select(selector='AccountService.', rel=True)[0].dict
                path = results[self._rdmc.app.typepath.defs.hrefstring]
                oem = results['Oem'][self.typepath.defs.oemhp]
                local_auth = results['LocalAccountAuth']
                results = results['ActiveDirectory']
                name = 'ActiveDirectory'
            except (KeyError, IndexError):
                raise NoContentsFoundForOperationError("Unable to gather Kerberos settings.")

        elif not args[0].lower() == 'test':
            raise InvalidCommandLineError("Please choose LDAP, Kerberos to read or modify "\
                                    "directory settings or test to test directory settings.")

        if results:
            keytab = None
            payload = {}
            if options.keytab:
                keytab = options.keytab
            try:
                directory_settings = self.directory_helper(results, options, args[1], args[2])
            except IndexError:
                directory_settings = self.directory_helper(results, options)

            if directory_settings:
                payload[name] = directory_settings

            if options.authmode:
                payload.update({'Oem':{'Hpe':{'DirectorySettings': \
                                              {'LdapAuthenticationMode': options.authmode}}}})
            
            if not payload and not keytab:
                if options.json:
                    UI().print_out_json({name: results, 'LocalAccountAuth': local_auth, \
                                         "Oem": {"Hpe": oem}})
                else:
                    self.print_settings(results, oem, local_auth, name)

            if payload:
                if options.localauth:
                    payload['LocalAccountAuth'] = 'Enabled' if options.localauth else 'Disabled'
                sys.stdout.write("Changing settings...\n")
                try:
                    self._rdmc.app.patch_handler(path, payload)
                except IloResponseError:
                    if len(args) == 3 and not results['ServiceEnabled']:
                        sys.stderr.write("You must enable this directory service before or during"\
                        " assignment of username and password. Try adding the flag --enable.\n")
                        raise IloResponseError("")
                    else:
                        raise
            if keytab:
                path = oem['Actions'][next(iter(oem['Actions']))]['target']
                sys.stdout.write("Adding keytab...\n")
                self._rdmc.app.post_handler(path, {"ImportUri": keytab})
        else:
            self.test_directory(args[1], json=options.json)

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Wrapper function for upload command main 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)

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            url = None
            self.uploadcommandvalidation(options)
        fwpkg = False
        if options.component.endswith('.fwpkg'):
            fwpkg = True
            comp, loc, ctype = self.fwpkgprepare(self, options.component)
            if ctype == 'C':
                options.component = comp[0]
            else:
                options.component = os.path.join(loc, comp[0])

        if options.sessionid and not url:
            raise InvalidCommandLineError('Url muse be included with sessionid. '\
                                      'Session is not required for local mode.')

        if not options.sessionid and self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        filestoupload = self._check_and_split_files(options)

        if self.componentvalidation(options, url, filestoupload):
            start_time = time.time()
            ret = ReturnCodes.FAILED_TO_UPLOAD_COMPONENT

            if not url and 'blobstore' in self._rdmc.app.get_current_client()\
                                                    ._rest_client.get_base_url():
                ret = self.uploadlocally(filestoupload, options)
            else:
                ret = self.uploadfunction(filestoupload, options, url)

            sys.stdout.write("%s\n" % human_readable_time(time.time() - start_time))

            if len(filestoupload) > 1:
                path, _ = os.path.split((filestoupload[0])[1])
                shutil.rmtree(path)
            elif fwpkg:
                shutil.rmtree(loc)
            if options.logout:
                self.logoutobj.run("")
        else:
            ret = ReturnCodes.SUCCESS

        return ret
    def run(self, line):
        """ Main listcomp worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            _subcommands = ['add', 'delete', 'invoke']
            found = False
            for i, arg in enumerate(line):
                if arg in _subcommands:
                    found = True
                    try:
                        if line[i +
                                1] not in self.parser._option_string_actions.keys(
                                ):
                            (options, args) = self._parse_arglist(line)
                        else:
                            raise IndexError
                    except (KeyError, IndexError):
                        (options, args) = self._parse_arglist(line,
                                                              default=True)
                    else:
                        continue
            if not found:
                (options, args) = self._parse_arglist(line, default=True)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.installsetvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                                    'only available on iLO 5.')

        if hasattr(options, 'name'):
            if options.name:
                if options.name.startswith('"') and options.name.endswith('"'):
                    options.name = options.name[1:-1]
        if hasattr(options, 'removeall'):
            if options.removeall:
                self.removeinstallsets()
        if options.command.lower() == 'add':
            if not options.json:
                raise InvalidCommandLineError(
                    'add command requires an install set file.')
            else:
                self.addinstallset(options.json, options.name)
        elif options.command.lower() == 'delete':
            self.deleteinstallset(options.name)
        elif options.command.lower() == 'invoke':
            self.invokeinstallset(options)
        else:
            self.printinstallsets(options)

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #25
0
    def run(self, line):
        """ Main firmware update 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("")

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

        self.firmwareintegritycheckvalidation(options)
        if self.rdmc.app.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.rdmc.app.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..."
            self.rdmc.ui.printer(results_string)
            polling = 50
            found = False
            while polling > 0:
                if not polling % 5:
                    self.rdmc.ui.printer('.')
                get_results = self.rdmc.app.get_handler(bodydict['@odata.id'],\
                    service=True, silent=True)
                if get_results:
                    curr_time = strptime(bodydict['Oem']['Hpe']\
                                        ['CurrentTime'], "%Y-%m-%dT%H:%M:%SZ")
                    scan_time = strptime(get_results.dict['Oem']['Hpe']\
                        ['FirmwareIntegrity']['LastScanTime'], "%Y-%m-%dT%H:%M:%SZ")

                    if scan_time > curr_time:
                        self.rdmc.ui.printer('\nScan Result: %s\n' % get_results.dict\
                                            ['Oem']['Hpe']['FirmwareIntegrity']['LastScanResult'])
                        found = True
                        break

                    polling -= 1
                    time.sleep(1)
            if not found:
                self.rdmc.ui.error(
                    '\nPolling timed out before scan completed.\n')
                TimeOutError("")

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #26
0
    def run(self, line):
        """ Main iloaccounts function

        :param line: string of arguments passed in
        :type line: str.
        """
        acct = mod_acct = None
        try:
            ident_subparser = False
            for cmnd in __subparsers__:
                if cmnd in line:
                    (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
                    ident_subparser = True
                    break
            if not ident_subparser:
                (options, args) = self.rdmc.rdmc_parse_arglist(self,
                                                               line,
                                                               default=True)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.iloaccountsvalidation(options)

        redfish = self.rdmc.app.monolith.is_redfish
        path = self.rdmc.app.typepath.defs.accountspath
        results = self.rdmc.app.get_handler(path, service=True,
                                            silent=True).dict

        if redfish:
            results = results['Members']
        else:
            if 'Member' in results['links']:
                results = results['links']['Member']
            else:
                results = list()

        for indx, acct in enumerate(results):
            acct = self.rdmc.app.get_handler(acct[self.rdmc.app.typepath.defs.hrefstring],\
                                                                service=True, silent=True).dict
            try:
                if hasattr(options, 'identifier'):
                    if acct['Id'] == options.identifier or acct[
                            'UserName'] == options.identifier:
                        if redfish:
                            path = acct['@odata.id']
                        else:
                            path = acct['links']['self']['href']
                        mod_acct = acct
                elif options.command == 'default':
                    results[indx] = acct
                else:
                    raise KeyError
            except KeyError:
                continue
            else:
                if mod_acct:
                    acct = mod_acct
                    break

        if not results:
            raise NoContentsFoundForOperationError(
                "No iLO Management Accounts were found.")

        outdict = dict()
        if options.command.lower() == 'default':
            if not options.json:
                self.rdmc.ui.printer("\niLO Account info:\n\n[Id] UserName (LoginName): "\
                                     "\nPrivileges\n-----------------\n\n", verbose_override=True)
            for acct in sorted(results, key=lambda k: int(k['Id'])):
                privstr = ""
                privs = acct['Oem'][
                    self.rdmc.app.typepath.defs.oemhp]['Privileges']

                if 'ServiceAccount' in list(acct['Oem'][self.rdmc.app.typepath.defs.oemhp].keys()) \
                        and acct['Oem'][self.rdmc.app.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'
                    self.rdmc.ui.printer("[%s] %s (%s):\n%s\n%s\n" % (acct['Id'], \
                                    acct['UserName'], \
                                    acct['Oem'][self.rdmc.app.typepath.defs.oemhp]['LoginName'], \
                                    service, privstr), verbose_override=True)
                keyval = '[' + str(acct['Id']) + '] ' + acct['UserName']
                outdict[keyval] = privs
                outdict[keyval]['ServiceAccount'] = service.split(
                    '=')[-1].lower()
            if options.json:
                self.rdmc.ui.print_out_json_ordered(outdict)
        elif options.command.lower() == 'changepass':
            if not acct:
                raise InvalidCommandLineError(
                    "Unable to find the specified account.")
            if not options.acct_password:
                self.rdmc.ui.printer('Please input the new password.\n',
                                     verbose_override=True)
                tempinput = getpass.getpass()
                self.credentialsvalidation('', '', tempinput, '', True,
                                           options)
                options.acct_password = tempinput
            account = options.identifier.lower()
            self.credentialsvalidation('', '',
                                       options.acct_password.split('\r')[0],
                                       '', True)
            body = {'Password': options.acct_password.split('\r')[0]}

            if path and body:
                self.rdmc.app.patch_handler(path, body)
            else:
                raise NoContentsFoundForOperationError(
                    'Unable to find the specified account.')

        elif options.command.lower() == 'add':
            if options.encode:
                args[2] = Encryption.decode_credentials(args[2])
                if isinstance(args[2], bytes):
                    args[2] = args[2].decode('utf-8')

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

            body = {"UserName": options.identifier, "Password": options.acct_password, "Oem": \
                    {self.rdmc.app.typepath.defs.oemhp: {"LoginName": options.loginname}}}
            if privs:
                body["Oem"][self.rdmc.app.typepath.defs.oemhp].update(
                    {"Privileges": privs})
            self.credentialsvalidation(options.identifier, options.loginname, \
                                       options.acct_password, acct, True)
            if options.serviceacc:
                body["Oem"][self.rdmc.app.typepath.defs.oemhp].update(
                    {"ServiceAccount": True})
            if options.role:
                if self.rdmc.app.getiloversion() >= 5.140:
                    body["RoleId"] = options.role
                else:
                    raise IncompatibleiLOVersionError("Roles can only be set in iLO 5"\
                                                                                " 1.40 or greater.")
            if path and body:
                self.rdmc.app.post_handler(path, body)
        elif options.command.lower() == 'modify':
            if not mod_acct:
                raise InvalidCommandLineError(
                    "Unable to find the specified account.")
            body = {}

            if options.optprivs:
                body.update({
                    'Oem': {
                        self.rdmc.app.typepath.defs.oemhp: {
                            'Privileges': {}
                        }
                    }
                })
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) \
                                                            and 'SystemRecoveryConfigPriv' not in \
                                                                        self.getsesprivs().keys():
                    raise IdTokenError("The currently logged in account must have The System "\
                                         "Recovery Config privilege to add the System Recovery "\
                                         "Config privilege.")
                privs = self.getprivs(options)
                body['Oem'][
                    self.rdmc.app.typepath.defs.oemhp]['Privileges'] = privs

            if options.role and self.rdmc.app.getiloversion() >= 5.140:
                body["RoleId"] = options.role

            if not body:
                raise InvalidCommandLineError("Valid Privileges/RoleID have not been provided; "\
                        " no changes have been made to this account: %s\n" % options.identifier)
            self.rdmc.app.patch_handler(path, body)

        elif options.command.lower() == 'delete':
            if not acct:
                raise InvalidCommandLineError(
                    "Unable to find the specified account.")
            self.rdmc.app.delete_handler(path)

        elif 'cert' in options.command.lower():
            certpath = '/redfish/v1/AccountService/UserCertificateMapping/'
            privs = self.getsesprivs()
            if self.rdmc.app.typepath.defs.isgen9:
                IncompatibleiLOVersionError("This operation is only available on gen 10 "\
                                                  "and newer machines.")
            elif not privs['UserConfigPriv']:
                raise IdTokenError("The currently logged in account must have The User "\
                                     "Config privilege to manage certificates for users.")
            else:
                if options.command.lower() == 'addcert':
                    if not acct:
                        raise InvalidCommandLineError(
                            "Unable to find the specified account.")
                    body = {}
                    username = acct['UserName']
                    account = acct['Id']
                    fingerprintfile = options.certificate
                    if os.path.exists(fingerprintfile):
                        with open(fingerprintfile, 'r') as fingerfile:
                            fingerprint = fingerfile.read()
                    else:
                        raise InvalidFileInputError('%s cannot be read.' %
                                                    fingerprintfile)
                    body = {"Fingerprint": fingerprint, "UserName": username}
                    self.rdmc.app.post_handler(certpath, body)

                elif options.command.lower() == 'deletecert':
                    if not acct:
                        raise InvalidCommandLineError(
                            "Unable to find the specified account.")
                    certpath += acct['Id']
                    self.rdmc.app.delete_handler(certpath)

        else:
            raise InvalidCommandLineError('Invalid command.')

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #27
0
    def run(self, line):
        """ Main fwpkg worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        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("")

        if self.rdmc.app.typepath.url:
            if 'http' not in self.rdmc.app.typepath.url:
                options.logout = True
                self.cmdbase.logout_routine(self, options)
        else:
            options.logout = True
            self.cmdbase.logout_routine(self, options)
        self.fwpkgvalidation(options)

        if self.rdmc.app.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError(\
                      'iLO Repository commands are only available on iLO 5.')

        if self.rdmc.app.getiloversion() <= 5.120 and options.fwpkg.lower(
        ).startswith('iegen10'):
            raise IncompatibleiLOVersionError('Please upgrade to iLO 5 1.20 or '\
                       'greater to ensure correct flash of this firmware.')
        tempdir = ''
        if not options.fwpkg.endswith('.fwpkg'):
            InvalidFileInputError("Invalid file type. Please make sure the file "\
                                  "provided is a valid .fwpkg file type.")

        try:
            components, tempdir, comptype = self.preparefwpkg(
                self, options.fwpkg)
            if comptype == 'D':
                raise InvalidFileInputError("Unable to flash this fwpkg file.")
            elif comptype == 'C':
                try:
                    self.taskqueuecheck()
                except TaskQueueError as excp:
                    if options.ignore:
                        self.rdmc.ui.warn(str(excp) + '\n')
                    else:
                        raise excp
            self.applyfwpkg(options, tempdir, components, comptype)

            if comptype == 'A':
                message = "Firmware has successfully been flashed.\n"
                if 'ilo' in options.fwpkg.lower():
                    message += "iLO will reboot to complete flashing. Session will be"\
                                " terminated.\n"
            elif comptype == 'B':
                message = "Firmware has successfully been flashed and a reboot is required for "\
                                                                "this firmware to take effect.\n"
            elif comptype == 'C':
                message = "This firmware is set to flash on reboot.\n"
            self.rdmc.ui.printer(message)

        except (FirmwareUpdateError, UploadError) as excp:
            raise excp

        finally:
            if tempdir:
                shutil.rmtree(tempdir)

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

        :param line: string of arguments passed in
        :type line: str.
        """
        mod_acct = None
        valid_args = ['add', 'delete', 'modify', 'changepass', 'addcert', 'deletecert']
        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) > 4:
            raise InvalidCommandLineError("Invalid number of parameters for "\
                                                                "this command.")
        arg_cnt = 0
        for arg in args:
            if arg in valid_args:
                arg_cnt += 1
        if arg_cnt > 1:
            raise InvalidCommandLineError('Invalid command.')

        self.iloaccountsvalidation(options)

        redfish = self._rdmc.app.monolith.is_redfish
        path = self.typepath.defs.accountspath
        results = self._rdmc.app.get_handler(path, service=True, silent=True).dict

        newresults = []

        if redfish:
            results = results['Members']
        else:
            results = results['links']['Member']

        for acct in results:
            acct = self._rdmc.app.get_handler(acct[self.typepath.defs.hrefstring],\
                                                                service=True, silent=True).dict
            if acct['Id'] in args or acct['UserName'] in args:
                mod_acct = acct
                if redfish:
                    path = acct['@odata.id']
                else:
                    path = acct['links']['self']['href']
            newresults.append(acct)
            results = newresults

        acct = mod_acct
        if not results:
            raise NoContentsFoundForOperationError("")

        outdict = dict()
        if not args:
            if not options.json:
                sys.stdout.write("iLO Account info: \n[Id] UserName (LoginName): "\
                                "\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 list(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['UserName']
                outdict[keyval] = privs
                outdict[keyval]['ServiceAccount'] = service.split('=')[-1].lower()
            if options.json:
                sys.stdout.write(str(json.dumps(outdict, indent=2, sort_keys=True)))
                sys.stdout.write('\n')
        elif args[0].lower() == 'changepass':
            if not mod_acct:
                raise InvalidCommandLineError("Unable to find the specified account.")
            if len(args) == 2:
                sys.stdout.write('Please input the new password.\n')
                tempinput = getpass.getpass()
                self.credentialsvalidation('', '', tempinput, '', True, options)
                args.extend([tempinput])
            if len(args) == 3:
                account = args[1].lower()
                if options.encode:
                    args[2] = Encryption.decode_credentials(args[2])
                self.credentialsvalidation('', '', args[2].split('\r')[0], '', True, options)
                body = {'Password': args[2].split('\r')[0]}

                if path and body:
                    self._rdmc.app.patch_handler(path, body)
                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()

                self.credentialsvalidation('', '', tempinput, '', True, options)
                args.extend([tempinput])

            if not len(args) == 3:
                raise InvalidCommandLineError('Invalid number of parameters.')

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

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

            body = {"UserName": args[0], "Password": args[2], "Oem": {self.\
                                        typepath.defs.oemhp: {"LoginName": args[1]}}}
            if privs:
                body["Oem"][self.typepath.defs.oemhp].update({"Privileges": privs})
            self.credentialsvalidation(args[0], args[1], args[2], results, True, options)
            if options.serviceacc:
                body["Oem"][self.typepath.defs.oemhp].update({"ServiceAccount": True})
            if options.role:
                if self._rdmc.app.getiloversion() >= 5.140:
                    body["RoleId"] = options.role
                else:
                    raise IncompatibleiLOVersionError("Roles can only be set in iLO 5"\
                                                                                " 1.40 or greater.")
            if path and body:
                self._rdmc.app.post_handler(path, body)
        elif args[0].lower() == 'modify':
            if not mod_acct:
                raise InvalidCommandLineError("Unable to find the specified account.")
            body = {}
            args.remove('modify')

            if not len(args) == 1:
                raise InvalidCommandLineError("Invalid number of parameters.")

            if options.optprivs:
                body.update({'Oem': {self.typepath.defs.oemhp: {'Privileges': {}}}})
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) \
                                                            and 'SystemRecoveryConfigPriv' not in \
                                                                        self.getsesprivs().keys():
                    raise IdTokenError("The currently logged in account must have The System "\
                                         "Recovery Config privilege to add the System Recovery "\
                                         "Config privilege.")
                privs = self.getprivs(options)
                body['Oem'][self.typepath.defs.oemhp]['Privileges'] = privs

            if options.role and self._rdmc.app.getiloversion >= 5.140:
                body["RoleId"] = options.role

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

        elif args[0].lower() == 'delete':
            if not mod_acct:
                raise InvalidCommandLineError("Unable to find the specified account.")
            self._rdmc.app.delete_handler(path)

        elif 'cert' in args[0].lower():
            certpath = '/redfish/v1/AccountService/UserCertificateMapping/'
            privs = self.getsesprivs()
            if self.typepath.defs.isgen9:
                IncompatibleiLOVersionError("This operation is only available on gen 10 "\
                                                  "and newer machines.")
            elif privs['UserConfigPriv'] == False:
                raise IdTokenError("The currently logged in account must have The User "\
                                     "Config privilege to manage certificates for users.")
            else:
                if args[0].lower() == 'addcert':
                    if not mod_acct:
                        raise InvalidCommandLineError("Unable to find the specified account.")
                    body = {}
                    args.remove('addcert')
                    username = acct['UserName']
                    account = acct['Id']
                    if not len(args) == 2:
                        raise InvalidCommandLineError("Invalid number of parameters.")
                    fingerprintfile = args[1]
                    if os.path.exists(fingerprintfile):
                        with open(fingerprintfile, 'r') as fingerfile:
                            fingerprint = fingerfile.read()
                    else:
                        raise InvalidFileInputError('%s cannot be read.' % fingerprintfile)
                    body = {"Fingerprint": fingerprint, "UserName": username}
                    self._rdmc.app.post_handler(certpath, body)
                
                elif args[0].lower() == 'deletecert':
                    if not mod_acct:
                        raise InvalidCommandLineError("Unable to find the specified account.")
                    args.remove('deletecert')
                    certpath += acct['Id']
                    self._rdmc.app.delete_handler(certpath)

        else:
            raise InvalidCommandLineError('Invalid command.')

        return ReturnCodes.SUCCESS
Beispiel #29
0
    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 (InvalidCommandLineErrorOPTS, SystemExit):
            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"})
                    if not options.nomonitor:
                        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'])

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """Main directory Function

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

        try:
            _subcommands = ['ldap', 'kerberos', 'test']
            found = False
            for i, arg in enumerate(line):
                if arg in _subcommands:
                    found = True
                    try:
                        if line[i+1] not in self.parser._option_string_actions.keys():
                            (options, args) = self._parse_arglist(line)
                        else:
                            raise IndexError
                    except (KeyError, IndexError):
                        (options, args) = self._parse_arglist(line, default=True)
                    else:
                        continue
            if not found:
                (options, args) = self._parse_arglist(line, default=True)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.directoryvalidation(options)

        if self._rdmc.app.getiloversion() < 5.140:
            raise IncompatibleiLOVersionError("Directory settings are only available on "\
                                                                        "iLO 5 1.40 or greater.")
        results = None
        if options.command.lower() == 'ldap' or ((True if options.ldap_kerberos == 'ldap' \
                                    else False) if hasattr(options, 'ldap_kerberos') else False):
            try:
                results = self._rdmc.app.select(selector='AccountService.', \
                                                                        path_refresh=True)[0].dict
                path = results[self._rdmc.app.typepath.defs.hrefstring]
                oem = results['Oem'][self.typepath.defs.oemhp]
                local_auth = results['LocalAccountAuth']
                results = results['LDAP']
                name = 'LDAP'
            except (KeyError, IndexError):
                raise NoContentsFoundForOperationError("Unable to gather LDAP settings.")

        elif options.command.lower() == 'kerberos' or ((True if options.ldap_kerberos == \
                        'kerberos' else False) if hasattr(options, 'ldap_kerberos') else False):
            try:
                results = self._rdmc.app.select(selector='AccountService.', \
                                                                        path_refresh=True)[0].dict
                path = results[self._rdmc.app.typepath.defs.hrefstring]
                oem = results['Oem'][self.typepath.defs.oemhp]
                local_auth = results['LocalAccountAuth']
                results = results['ActiveDirectory']
                name = 'ActiveDirectory'
            except (KeyError, IndexError):
                raise NoContentsFoundForOperationError("Unable to gather Kerberos settings.")

        if results:
            keytab = None
            payload = {}
            if hasattr(options, 'keytab'):
                keytab = options.keytab
            try:
                directory_settings = self.directory_helper(results, options)
            except IndexError:
                directory_settings = self.directory_helper(results, options)

            if directory_settings:
                payload[name] = directory_settings

            if hasattr(options, 'authmode'):
                if options.authmode:
                    payload.update({'Oem':{'Hpe':{'DirectorySettings': \
                                              {'LdapAuthenticationMode': options.authmode}}}})

            if not payload and not keytab:
                if options.json:
                    UI().print_out_json({name: results, 'LocalAccountAuth': local_auth, \
                                         "Oem": {"Hpe": oem}})
                else:
                    self.print_settings(results, oem, local_auth, name)

            if payload:
                priv_patches = {}
                try:
                    if hasattr(options, "localauth"):
                        if options.localauth:
                            payload['LocalAccountAuth'] = 'Enabled' \
                                                            if options.localauth else 'Disabled'
                    elif local_auth:
                        payload['LocalAccountAuth'] = 'Enabled' if local_auth else 'Disabled'
                except NameError, AttributeError:
                    payload['LocalAccountAuth'] = 'Disabled'
                try:
                    maps = {}
                    if payload.get('LDAP'):
                        maps = payload['LDAP'].get('RemoteRoleMapping', {})
                    elif payload.get('ActiveDirectory'):
                        maps = payload['ActiveDirectory'].get('RemoteRoleMapping', {})
                        #Check if we need to modify roles after creating
                        for mapping in maps:
                            privs = mapping['LocalRole'].split(';')
                            if len(privs) > 1:
                                privs = [int(priv) for priv in privs if priv]
    
                                if 10 in privs:
                                    user_privs = self.iloaccounts.getsesprivs()
                                    if 'SystemRecoveryConfigPriv' not in user_privs.keys():
                                        raise IdTokenError("The currently logged in account "\
                                        "must have the System Recovery Config privilege to "\
                                        "add the System Recovery Config privilege to a local "\
                                        "role group.")
    
                                priv_patches[mapping['RemoteGroup']] = privs
                                mapping['LocalRole'] = "ReadOnly"
                except Exception:
                    pass
                sys.stdout.write("Changing settings...\n")
                try:
                    self._rdmc.app.patch_handler(path, payload)
                except IloResponseError:
                    if not results['ServiceEnabled']:
                        sys.stderr.write("You must enable this directory service before or during"\
                        " assignment of username and password. Try adding the flag --enable.\n")
                        raise IloResponseError("")
                    else:
                        raise
                if priv_patches:
                    self.update_mapping_privs(priv_patches)
            if keytab:
                path = oem['Actions'][next(iter(oem['Actions']))]['target']
                sys.stdout.write("Adding keytab...\n")
                self._rdmc.app.post_handler(path, {"ImportUri": keytab})