def __init__(self, host, user=None, password=None, session_key=None): """ Object initialization method :param host: iLO sub-system IP or FQDN :param user: A user in iLO sub-system realm :param password: Password of the above user :param session_key: Session key """ url = "https://{}".format(host) self.client = redfish_client(base_url=url, username=user, password=password, sessionkey=session_key) if not session_key: # With SSO, the user is already logged into a manager hence login # should not be called. self.client.login(auth=AuthMethod.SESSION) self.type_path = tpdefs.Typesandpathdefines() self.type_path.getgen(url=url) self.type_path.defs.redfishchange() self.SYS_RESOURCE = self._get_resource_directory() self.MSG_REGISTRY = self._get_base_registry()
def login(host, username, password): session = redfish.redfish_client(base_url="https://"+host, \ username=username, \ password=password, \ default_prefix="/redfish/v1") session.login(auth="session") return session
def loadRedfish(self): login_host = "https://{}".format(os.environ['ILO_IP']) login_account = os.environ['ILO_USERNAME'] login_password = os.environ['ILO_PASSWORD'] self.redfishObj = redfish.redfish_client(base_url=login_host, username=login_account, password=login_password)
def redfish_login(self): self.rf_obj = redfish.redfish_client( base_url=self.host, username=self.user, password=self.pwd, default_prefix=self.default_prefix) self.rf_obj.login(auth="session")
def login(self, target, username, password, config): self.rc = redfish.redfish_client(base_url=target, username=username, password=password, default_prefix=config['redfish_base_path'], timeout=30, max_retry=None) self.rc.login(auth="session")
def get_server_boot_once(ip, login_account, login_password, system_id): """Get server boot once item :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params system_id: ComputerSystem instance id(None: first instance, All: all instances) :type system_id: None or string :returns: returns server boot once item when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) # Login into the server and create a session REDFISH_OBJ.login(auth=utils.g_AUTH) except: traceback.print_exc() result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} return result # GET the ComputerSystem resource boot_details = [] system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) if not system: result = {'ret': False, 'msg': "This system id is not exist or system member is None"} REDFISH_OBJ.logout() return result for i in range(len(system)): system_url = system[i] response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status == 200: # Get the response boot_server = {} properties = ['BootSourceOverrideEnabled', 'BootSourceOverrideMode', 'BootSourceOverrideTarget'] for property in properties: if property in response_system_url.dict["Boot"]: boot_server[property] = response_system_url.dict["Boot"][property] boot_details.append(boot_server) else: result = {'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status} REDFISH_OBJ.logout() return result result['ret'] = True result['entries'] = boot_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def getgen(self, gen=None, url=None, username=None, password=None, logger=None): """Function designed to verify the servers platform :param url: The URL to perform the request on. :type url: str. :param logger: The logger handler. :type logger: str. """ self.url = url if not gen: try: redfishclient = redfish_client(base_url=self.url, \ username=username, password=password, \ default_prefix="/redfish/v1/", is_redfish=True,\ cache=False) rootresp = redfishclient.root redfishclient.logout() except SecurityStateError as excp: raise excp except InvalidCredentialsError: raise except Exception: excep = None try: restclient = rest_client(base_url=self.url, username=username, \ password=password, default_prefix="/rest/v1") rootresp = restclient.root restclient.logout() except Exception as excep: logger = logger if not logger else LOGGER logger.error("Gen get rest error:"+str(excep)+"\n") if excep: raise self.ilogen = None try: self.ilogen = rootresp["Oem"]["Hp"]["Manager"][0]["ManagerType"] except: self.ilogen = rootresp["Oem"]["Hpe"]["Manager"][0]["ManagerType"] else: self.ilogen = int(gen) try: if not isinstance(self.ilogen, int): self.ilogen = self.ilogen.split(' ')[-1] self.flagiften = False if int(self.ilogen) >= 5: self.flagiften = True except: raise UnableToObtainIloVersionError("Unable to find the iloversion") if self.flagiften: self.defs = Definevalstenplus() else: self.defs = DefinevalsNine()
def init_connection(self, reset=False): # reset connection if reset is True: self.connection = None # if we have a connection object then just return if self.connection is not None: return self.get_credentials() # initialize connection try: self.connection = redfish.redfish_client( base_url="https://%s" % self.cli_args.host, max_retry=self.cli_args.retries, timeout=self.cli_args.timeout) except redfish.rest.v1.ServerDownOrUnreachableError: self.exit_on_error( "Host '%s' down or unreachable." % self.cli_args.host, "CRITICAL") except redfish.rest.v1.RetriesExhaustedError: self.exit_on_error( "Unable to connect to Host '%s', max retries exhausted." % self.cli_args.host, "CRITICAL") except Exception as e: self.exit_on_error( "Unable to connect to Host '%s': %s" % (self.cli_args.host, str(e)), "CRITICAL") if not self.connection: raise Exception("Unable to establish connection.") if self.username is not None or self.password is not None: try: self.connection.login(username=self.username, password=self.password, auth="session") except redfish.rest.v1.RetriesExhaustedError: self.exit_on_error( "Unable to connect to Host '%s', max retries exhausted." % self.cli_args.host, "CRITICAL") except redfish.rest.v1.InvalidCredentialsError: self.exit_on_error("Username or password invalid.", "CRITICAL") except Exception as e: self.exit_on_error( "Unable to connect to Host '%s': %s" % (self.cli_args.host, str(e)), "CRITICAL") if self.connection is not None: self.connection.system_properties = None if self.cli_args.nosession is False: self.save_session_to_file() return
def _get_client(self): login_host = self.config['login_host'] login_account = self.config['login_account'] login_password = self.config['login_password'] ## Create a REDFISH object client = redfish.redfish_client(base_url=login_host, username=login_account, \ password=login_password, default_prefix='/redfish/v1') return client
def __init__(self, host, login_account, login_password): try: self.redfish_client = redfish_client(base_url=host, \ username=login_account, password=login_password, \ default_prefix="/redfish/v1") except: raise self.redfish_client.login(auth=AuthMethod.SESSION) self.SYSTEMS_RESOURCES = self.ex1_get_resource_directory() self.MESSAGE_REGISTRIES = self.ex2_get_base_registry()
def set_chassis_indicator_led(ip, login_account, login_password, led_status): """Get BMC inventory :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params led_status: Led status by user specified :type led_status: string :returns: returns set chassis indicator led result when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, password=login_password, default_prefix='/redfish/v1') # Login into the server and create a session REDFISH_OBJ.login(auth="session") except: result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} return result # Get ComputerBase resource response_base_url = REDFISH_OBJ.get('/redfish/v1', None) # Get response_base_url if response_base_url.status == 200: chassis_url = response_base_url.dict['Chassis']['@odata.id'] else: result = {'ret': False, 'msg': "response base url Error code %s" % response_base_url.status} REDFISH_OBJ.logout() return result # Get response chassis url resource response_chassis_url = REDFISH_OBJ.get(chassis_url, None) if response_chassis_url.status == 200: for i in range(response_chassis_url.dict['*****@*****.**']): led_url = response_chassis_url.dict['Members'][i]['@odata.id'] led_status = led_status parameter = {"IndicatorLED": led_status} headers = {"Content-Type": "application/json"} response_url = REDFISH_OBJ.patch(led_url, body=parameter, headers=headers) if response_url.status == 200: result = {'ret': True, 'msg': "PATCH command successfully completed '%s' request for chassis indicator LED" % led_status} else: result = {'ret': False, 'msg': "response url Error code %s" % response_url.status} REDFISH_OBJ.logout() return result else: print("response_chassis_url Error code %s" % response_chassis_url.status) result = {'ret': False, 'msg': "response chassis url Error code %s" % response_chassis_url.status} REDFISH_OBJ.logout() return result
def _create_session(ip, login_account): '''Creates an authenticated session to the Redfish API''' login_password = getpass.getpass(prompt='Enter the IMM password: '******'/redfish/v1') REDFISH_OBJ.login(auth="session")
def __init__(self, host, token): try: self.redfish_client = redfish_client(base_url=host, sessionkey=token, default_prefix="/redfish/v1") except: raise self.typepath = redfish.ris.tpdefs.Typesandpathdefines() self.typepath.getgen(url=host, logger=LOGGER) self.typepath.defs.redfishchange() self.SYSTEMS_RESOURCES = self.ex1_get_resource_directory() self.MESSAGE_REGISTRIES = self.ex2_get_base_registry()
def __init__(self, host, login_account, login_password): try: self.redfish_client = redfish_client(base_url=host, \ username=login_account, password=login_password) except: raise self.typepath = redfish.ris.tpdefs.Typesandpathdefines() self.typepath.getgen(url=host, logger=LOGGER) self.typepath.defs.redfishchange() self.redfish_client.login(auth=AuthMethod.SESSION) self.SYSTEMS_RESOURCES = self.ex1_get_resource_directory() self.MESSAGE_REGISTRIES = self.ex2_get_base_registry()
def _get_client(self): login_host = self.config['login_host'] login_account = self.config['login_account'] login_password = self.config['login_password'] ### Create a REDFISH object client = redfish.redfish_client(base_url=login_host, username=login_account, password=login_password, default_prefix='/redfish/v1') # Login into the server and create a session client.login(auth="session") return client
def __init__(self, host, login_account, login_password): try: self.redfish_client = redfish_client(base_url=host, \ username=login_account, password=login_password, \ default_prefix="/redfish/v1") except: raise self.typepath = redfish.ris.tpdefs.Typesandpathdefines() self.typepath.getgen(url=host, logger=LOGGER) self.typepath.defs.redfishchange() self.redfish_client.login(auth=AuthMethod.SESSION) self.SYSTEMS_RESOURCES = self.ex1_get_resource_directory() self.MESSAGE_REGISTRIES = self.ex2_get_base_registry()
def raw_command_patch(ip, login_account, login_password, resource_uri, body): """Patch specified resource :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params resource_uri: redfish resource uri :type resource_uri: string :params body: json string body for redfish patch request :type body: string :returns: returns specified resource information when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) # Login into the server and create a session REDFISH_OBJ.login(auth=utils.g_AUTH) except Exception as e: traceback.print_exc() result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} return result request_url = resource_uri headers = {"If-Match": "*"} response_url = REDFISH_OBJ.patch(request_url, body=json.loads(body), headers=headers) if response_url.status not in [200, 204]: error_message = utils.get_extended_error(response_url) result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( request_url, response_url.status, error_message)} REDFISH_OBJ.logout() return result message_extendedinfo = "" if response_url.status == 200 and "@Message.ExtendedInfo" in response_url.dict: message_extendedinfo = "@Message.ExtendedInfo: " + str(response_url.dict["@Message.ExtendedInfo"]) result['ret'] = True result['msg'] = "Update resource uri %s successfully. %s" %(resource_uri, message_extendedinfo) # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def getgen(self, url=None, logger=None): """Function designed to verify the servers platform :param url: The URL to perform the request on. :type url: str. :param logger: The logger handler. :type logger: str. """ self.url = url try: redfishclient = redfish_client(base_url=self.url, \ username=None, password=None, \ default_prefix="/redfish/v1/", is_redfish=True) response = redfishclient.get(path="/redfish/v1/") except SecurityStateError as excp: raise excp except Exception as excp: try: restclient = rest_client(base_url=self.url, username=None, \ password=None, default_prefix="/rest/v1") response = restclient.get(path="/rest/v1") except Exception as excep: logger = logger if not logger else LOGGER if type(excep) != type(excp): logger.error("Gen get rest error:" + str(excep) + "\n") raise excp self.ilogen = None try: self.ilogen = response.dict["Oem"]["Hp"]["Manager"][0]\ ["ManagerType"] except: self.ilogen = response.dict["Oem"]["Hpe"]["Manager"][0]\ ["ManagerType"] try: self.ilogen = self.ilogen.split(' ')[-1] self.flagiften = False if int(self.ilogen) >= 5: self.flagiften = True except: raise UnableToObtainIloVersionError( "Unable to find the iloversion") if self.flagiften: self.defs = Definevalstenplus() else: self.defs = DefinevalsNine()
def loadRedfish(self): if not self.ip_address: self.ip_address = os.environ['ILO_IP'] if not self.username: self.username = os.environ['ILO_USERNAME'] if not self.password: self.password = os.environ['ILO_PASSWORD'] login_host = "https://{}".format(self.ip_address) self.redfishObj = redfish.redfish_client(base_url=login_host, username=self.username, password=self.password)
def __init__(self, host_ip, username, password): r""" initialize redfish client connection to host. """ self.base_url = "https://" + host_ip self.username = username self.password = password self.default_prefix = "/redfish/v1" self.robj = redfish.redfish_client(base_url=self.base_url, username=self.username, password=self.password, default_prefix=self.default_prefix) self.robj.login(auth="session") self.session_key = self.robj.get_session_key()
def raw_command_get(ip, login_account, login_password, resource_uri): """Get specified resource information :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params resource_uri: redfish resource uri :type resource_uri: string :returns: returns specified resource information when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) # Login into the server and create a session REDFISH_OBJ.login(auth=utils.g_AUTH) except Exception as e: traceback.print_exc() result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} return result request_url = resource_uri response_url = REDFISH_OBJ.get(request_url, None) if response_url.status != 200: error_message = utils.get_extended_error(response_url) result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( request_url, response_url.status, error_message)} REDFISH_OBJ.logout() return result resource_details = response_url.dict result['ret'] = True result['data'] = resource_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def __init__(self, host, account, password, use_ssl=True, connection_retries=10): try: if use_ssl: redfish_url = 'https://' + host else: redfish_url = 'http://' + host self.redfish_client = redfish_client(base_url=redfish_url, username=account, password=password) self.redfish_client.MAX_RETRY = connection_retries self.redfish_client.login(auth=AuthMethod.SESSION) except RetriesExhaustedError: raise RedfishException("Login failed: Retries exhausted") except InvalidCredentialsError: raise RedfishException("Login failed: Invalid credentials") except ServerDownOrUnreachableError: raise RedfishException("Login failed: Server unreachable")
def _init_connection(self, driver_info): """Get connection info and init rest_object""" host = 'https://' + driver_info['address'] user = driver_info['username'] password = driver_info['password'] redfishclient = None try: redfishclient = redfish_client(base_url=host, \ username=user, password=password, \ default_prefix="/redfish/v1") redfishclient.login(auth=AuthMethod.SESSION) self._init_typepath(redfishclient) except ServerDownOrUnreachableError as error: operation = _("iLO not responding") raise virtmedia_exception.VirtmediaOperationError( operation=operation, error=error) except Exception as error: operation = _("Failed to login to iLO") raise virtmedia_exception.VirtmediaOperationError( operation=operation, error=error) return redfishclient
def _init_connection(self, driver_info): """Get connection info and init rest_object""" host = 'https://' + driver_info['address'] user = driver_info['username'] password = driver_info['password'] redfishclient = None self.log.debug("Init connection: user: %s, passwd: %s, host: %s", user, password, host) try: redfishclient = redfish_client(base_url=host, \ username=user, password=password) redfishclient.login(auth=AuthMethod.SESSION) except ServerDownOrUnreachableError as error: operation = _("iDRAC not responding") raise virtmedia_exception.VirtmediaOperationError( operation=operation, error=error) except Exception as error: operation = _("Failed to login to iDRAC") raise virtmedia_exception.VirtmediaOperationError( operation=operation, error=error) return redfishclient
def main(): with open( "/Users/avimor/Downloads/ceph-ansible-rhcs-4-vagrant3/serverlist.txt", "r") as f: lines = f.read().splitlines() for host in lines: try: ilo_url = host SYSTEM_URL = ilo_url LOGIN_ACCOUNT = "admin" LOGIN_PASSWORD = "******" print(SYSTEM_URL) redfish_obj = redfish.redfish_client(base_url=SYSTEM_URL, username=LOGIN_ACCOUNT, password=LOGIN_PASSWORD) redfish_obj.login() connection(redfish_obj) except ServerDownOrUnreachableError as e: sys.stderr.write( "ERROR: server not reachable or does not support RedFish.\n" ) sys.exit()
def connect(self, timeout=7): "Connect to Redfish device(s)" try: self.client = redfish.redfish_client( base_url=self.url, username=self.credentials.username, password=self.credentials.password, timeout=timeout, max_retry=3) self.client.login(auth='session') self.connected = True except redfish.rest.v1.RetriesExhaustedError as ex: LOGGER.error(f"Error while logging in: Too many retires\n{ex}") return False except json.decoder.JSONDecodeError as ex: LOGGER.error( f"Error while logging in: Wrong server response\n{ex}") return False except redfish.rest.v1.InvalidCredentialsError as ex: LOGGER.error(f"Error while logging in: Invalid credentials\n{ex}") return False return True
def get_psu_inventory(ip, login_account, login_password, system_id): """Get power supply unit inventory :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params system_id: ComputerSystem instance id(None: first instance, All: all instances) :type system_id: None or string :returns: returns power supply unit inventory when succeeded or error message when failed """ result = {} psu_details = [] login_host = 'https://' + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) # Login into the server and create a session REDFISH_OBJ.login(auth=utils.g_AUTH) except Exception as e: traceback.print_exc() result = { 'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e) } return result # GET the ComputerSystem resource system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) if not system: result = { 'ret': False, 'msg': "This system id is not exist or system member is None" } REDFISH_OBJ.logout() return result for i in range(len(system)): system_url = system[i] response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status == 200: # Get the Chassis resource chassis_url = response_system_url.dict['Links']['Chassis'][0][ '@odata.id'] else: result = { 'ret': False, 'msg': "response system url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result response_chassis_url = REDFISH_OBJ.get(chassis_url, None) if response_chassis_url.status == 200: # Get the power_url_list power_url = response_chassis_url.dict['Power']['@odata.id'] else: result = { 'ret': False, 'msg': "response chassis url Error code %s" % response_chassis_url.status } REDFISH_OBJ.logout() return result response_power_url = REDFISH_OBJ.get(power_url, None) if response_power_url.status == 200: if 'PowerSupplies' not in response_power_url.dict: result = { 'ret': False, 'msg': "There is no PowerSupplies data in %s" % power_url } REDFISH_OBJ.logout() return result power_supply_list = response_power_url.dict['PowerSupplies'] for PowerSupplies in power_supply_list: entry = {} for property in [ 'Name', 'SerialNumber', 'PowerOutputWatts', 'EfficiencyPercent', 'LineInputVoltage', 'PartNumber', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerInputWatts', 'Model', 'PowerSupplyType', 'Status', 'Manufacturer', 'HotPluggable', 'LastPowerOutputWatts', 'InputRanges', 'LineInputVoltageType', 'Location' ]: if property in PowerSupplies: entry[property] = PowerSupplies[property] if 'Oem' in PowerSupplies and 'Lenovo' in PowerSupplies['Oem']: entry['Oem'] = {'Lenovo': {}} for oemprop in [ 'FruPartNumber', 'ManufactureDate', 'ManufacturerName' ]: if oemprop in PowerSupplies['Oem']['Lenovo']: entry['Oem']['Lenovo'][oemprop] = PowerSupplies[ 'Oem']['Lenovo'][oemprop] psu_details.append(entry) else: result = { 'ret': False, 'msg': "response power url Error code %s" % response_power_url.status } REDFISH_OBJ.logout() return result result['ret'] = True result['entry_details'] = psu_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def lenovo_create_raid_volume(ip, login_account, login_password, system_id, raidid, volume_name, raid_type, volume_capacity, read_policy, write_policy, io_policy, access_policy, drive_cache_policy): """Create raid volume :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params system_id: ComputerSystem instance id(None: first instance, All: all instances) :type system_id: None or string :params raidid: storage id :type raidid: string :params volume_name: name of the volume :type volume_name: string :params raid_type: raid type of the volume :type raid_type: string :params volume_capacity: capacity byte of the volume :type volume_capacity: int :params read_policy: read policy of the volume :type read_policy: string :params write_policy: write policy of the volume :type write_policy: string :params io_policy: io policy of the volume :type io_policy: string :params access_policy: access policy of the volume :type access_policy: string :params drive_cache_policy: drive cache policy of the volume :type drive_cache_policy: string :returns: returns storage inventory when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) # Login into the server and create a session REDFISH_OBJ.login(auth=utils.g_AUTH) except: result = { 'ret': False, 'msg': "Please check the username, password, IP is correct" } return result storage_details = [] # GET the ComputerSystem resource system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) if not system: result = { 'ret': False, 'msg': "This system id is not exist or system member is None" } REDFISH_OBJ.logout() return result target_raid_volumes_url = None for i in range(len(system)): system_url = system[i] response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status != 200: result = { 'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result if "Storage" not in response_system_url.dict: continue #skip the invalid ComputeSystem that has no storage resource # GET the Storage resources from the ComputerSystem resource storage_url = response_system_url.dict["Storage"]["@odata.id"] response_storage_url = REDFISH_OBJ.get(storage_url, None) if response_storage_url.status != 200: result = { 'ret': False, 'msg': "response storage url Error code %s" % response_storage_url.status } REDFISH_OBJ.logout() storage_count = response_storage_url.dict["*****@*****.**"] if storage_count == 0: continue #skip the invalid ComputeSystem that has no storage resource # Collect all storage info first list_raid_id = [] list_raid_name = [] list_raid_drive_num = [] list_raid_volume_num = [] list_raid_volume_urls = [] for raid_index in range(0, storage_count): storage_x_url = response_storage_url.dict["Members"][raid_index][ "@odata.id"] response_storage_x_url = REDFISH_OBJ.get(storage_x_url, None) if response_storage_x_url.status != 200: result = { 'ret': False, 'msg': "response_storage_x_url code %s" % response_storage_x_url.status } REDFISH_OBJ.logout() return result Storage_id = response_storage_x_url.dict["Id"] Name = response_storage_x_url.dict["Name"] drive_num = len(response_storage_x_url.dict["Drives"]) volumes_url = response_storage_x_url.dict["Volumes"]["@odata.id"] response_volumes_url = REDFISH_OBJ.get(volumes_url, None) if response_volumes_url.status != 200: error_message = utils.get_extended_error(response_volumes_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (volumes_url, response_volumes_url.status, error_message) } return result volume_num = len(response_volumes_url.dict["Members"]) list_raid_id.append(Storage_id) list_raid_name.append(Name) list_raid_drive_num.append(drive_num) list_raid_volume_num.append(volume_num) list_raid_volume_urls.append(volumes_url) # Found the target storage when raidid is specified if raidid is not None: for raid_index in range(0, storage_count): if raidid == list_raid_id[ raid_index] or raidid == list_raid_name[raid_index]: if list_raid_drive_num[raid_index] == 0: result = { 'ret': False, 'msg': "There is no Drives on specified storage %s" % (raidid) } REDFISH_OBJ.logout() return result if list_raid_volume_num[raid_index] != 0: result = { 'ret': False, 'msg': "Volume has already been created on specified storage %s" % (raidid) } REDFISH_OBJ.logout() return result target_raid_volumes_url = list_raid_volume_urls[raid_index] break # Check whether only one raid storage can be configured when raidid is not specified. If multi-raid can be configured, raidid need to be specified else: for raid_index in range(0, storage_count): if list_raid_drive_num[raid_index] == 0: continue if list_raid_volume_num[raid_index] != 0: continue if target_raid_volumes_url is None: target_raid_volumes_url = list_raid_volume_urls[raid_index] else: result = { 'ret': False, 'msg': "There are multi-storage which can be configured. Please specified the raidid. raidid list: %s" % (str(list_raid_id)) } REDFISH_OBJ.logout() return result if target_raid_volumes_url is None: result = { 'ret': False, 'msg': "Failed to found storage that can be configured" } REDFISH_OBJ.logout() return result # USE POST to create a volume headers = {"Content-Type": "application/json"} parameter = { "Name": volume_name, "RAIDType": raid_type, "CapacityBytes": volume_capacity, "Oem": { "Lenovo": {} } } if read_policy is not None: parameter["Oem"]["Lenovo"]["ReadPolicy"] = read_policy if write_policy is not None: parameter["Oem"]["Lenovo"]["WritePolicy"] = write_policy if io_policy is not None: parameter["Oem"]["Lenovo"]["IOPolicy"] = io_policy if access_policy is not None: parameter["Oem"]["Lenovo"]["AccessPolicy"] = access_policy if drive_cache_policy is not None: parameter["Oem"]["Lenovo"]["DriveCachePolicy"] = drive_cache_policy response_create_volume = REDFISH_OBJ.post(target_raid_volumes_url, body=parameter, headers=headers) if response_create_volume.status in [200, 201]: rt_link = login_host + "/" + response_create_volume.dict[ "@odata.id"] id = rt_link.split("/")[-1] result = { "ret": True, "msg": "Create volume successfully, volume id is " + id + ", volume 's link is:" + rt_link } try: REDFISH_OBJ.logout() except: pass return result else: error_message = utils.get_extended_error(response_create_volume) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (target_raid_volumes_url, response_create_volume.status, error_message) } REDFISH_OBJ.logout() return result if target_raid_volumes_url is None: result = { 'ret': False, 'msg': "Failed to found storage that can be configured" } # Logout of the current session REDFISH_OBJ.logout() return result
def get_power_redundancy(ip, login_account, login_password): """Get power redundancy :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :returns: returns Get power redundant result when succeeded or error message when failed """ result = {} login_host = "https://" + ip # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) # Login into the server and create a session try: REDFISH_OBJ.login(auth=utils.g_AUTH) except: traceback.print_exc() result = { 'ret': False, 'msg': "Please check the username, password, IP is correct\n" } return result # Get ServiceBase resource try: response_base_url = REDFISH_OBJ.get('/redfish/v1', None) # Get response_base_url if response_base_url.status == 200: chassis_url = response_base_url.dict['Chassis']['@odata.id'] else: error_message = utils.get_extended_error(response_base_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ('/redfish/v1', response_base_url.status, error_message) } return result response_chassis_url = REDFISH_OBJ.get(chassis_url, None) if response_chassis_url.status == 200: rt_list_redundant = [] #Get power redundant for request in response_chassis_url.dict['Members']: request_url = request['@odata.id'] response_url = REDFISH_OBJ.get(request_url, None) if response_url.status == 200: # if chassis is not normal skip it if len(response_chassis_url.dict['Members']) > 1 and ( "Links" not in response_url.dict or "ComputerSystems" not in response_url.dict["Links"]): continue # if no Power property, skip it if "Power" not in response_url.dict: continue power_url = response_url.dict["Power"]['@odata.id'] response_power_url = REDFISH_OBJ.get(power_url, None) if response_power_url.status == 200: # if no Redundancy property, skip it if "Redundancy" not in response_power_url.dict: continue list_power_redundancy = response_power_url.dict[ "Redundancy"] for redundancy_item in list_power_redundancy: dict_power_redundant = {} for key in redundancy_item: if key == "RedundancySet": continue if key not in [ "Description", "@odata.context", "@odata.id", "@odata.type", "@odata.etag", "Links", "Actions", "RelatedItem" ]: dict_power_redundant[ key] = redundancy_item[key] rt_list_redundant.append(dict_power_redundant) else: error_message = utils.get_extended_error( response_power_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (power_url, response_power_url.status, error_message) } return result else: error_message = utils.get_extended_error(response_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (request_url, response_url.status, error_message) } return result if len(rt_list_redundant) > 0: result["ret"] = True result["entries"] = rt_list_redundant else: result = {'ret': False, 'msg': "No Redundancy found"} return result else: error_message = utils.get_extended_error(response_chassis_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (chassis_url, response_chassis_url.status, error_message) } return result except Exception as e: traceback.print_exc() result = {'ret': False, 'msg': 'exception msg %s' % e} return result finally: try: REDFISH_OBJ.logout() except: pass
def get_system_inventory(ip, login_account, login_password, system_id): """Get system inventory :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: string :params system_id: ComputerSystem instance id(None: first instance, All: all instances) :type system_id: None or string :returns: returns system info when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the BMC address, account name, and password # Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) # Login into the server and create a session REDFISH_OBJ.login(auth=utils.g_AUTH) except: traceback.print_exc() result = { 'ret': False, 'msg': "Please check the username, password, IP is correct" } return result system_properties = [ 'Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'SystemType', 'PartNumber', 'SerialNumber', 'AssetTag', 'ServiceTag', 'UUID', 'SKU', 'BiosVersion', 'ProcessorSummary', 'MemorySummary', 'TrustedModules' ] lenovo_oem_properties = [ 'FrontPanelUSB', 'SystemStatus', 'NumberOfReboots', 'TotalPowerOnHours' ] system_details = [] # GET the ComputerSystem resource system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) if not system: result = { 'ret': False, 'msg': "This system id is not exist or system member is None" } REDFISH_OBJ.logout() return result for i in range(len(system)): system_url = system[i] response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status == 200: system = {} # Get the system information for system_property in system_properties: if system_property in response_system_url.dict: system[system_property] = response_system_url.dict[ system_property] if 'Oem' in response_system_url.dict and 'Lenovo' in response_system_url.dict[ 'Oem']: system['Oem'] = {'Lenovo': {}} for oem_property in lenovo_oem_properties: if oem_property in response_system_url.dict['Oem'][ 'Lenovo']: system['Oem']['Lenovo'][ oem_property] = response_system_url.dict['Oem'][ 'Lenovo'][oem_property] # GET System EtherNetInterfaces resources nics_url = response_system_url.dict["EthernetInterfaces"][ "@odata.id"] response_nics_url = REDFISH_OBJ.get(nics_url, None) if response_nics_url.status == 200: nic_count = response_nics_url.dict["*****@*****.**"] else: result = { 'ret': False, 'msg': "response nics url Error code %s" % response_nics_url.status } REDFISH_OBJ.logout() return result x = 0 ethernetinterface = [] for x in range(0, nic_count): EtherNetInterfaces = {} nic_x_url = response_nics_url.dict["Members"][x]["@odata.id"] response_nic_x_url = REDFISH_OBJ.get(nic_x_url, None) if response_nic_x_url.status == 200: if "PermanentMACAddress" in response_nic_x_url.dict: PermanentMACAddress = response_nic_x_url.dict[ "PermanentMACAddress"] EtherNetInterfaces[ 'PermanentMACAddress'] = PermanentMACAddress ethernetinterface.append(EtherNetInterfaces) else: result = { 'ret': False, 'msg': "response nic_x_url Error code %s" % response_nic_x_url.status } REDFISH_OBJ.logout() return result system['EtherNetInterfaces'] = ethernetinterface system_details.append(system) else: result = { 'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result result['ret'] = True result['entries'] = system_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
# Redirect standard output into a file(optional) if args.OutputFileName != None: if (args.OutputFileName.find('.txt') == -1): args.OutputFileName += ".txt" sys.stdout = open(args.OutputFileName, "w") # Connect using iLO Amplifier Pack address, username and password login_host = "https://" + args.iLOAmpAddress login_account = args.Username login_password = args.Password ## Create a REDFISH object try: REDFISH_OBJ = redfish.redfish_client(base_url=login_host, \ username=login_account, \ password=login_password, timeout=10, max_retry=3) except: print( "Wrong iLO Amplifier Pack address/credential or iLO Amplifier Pack is not reachable\n" ) exit() # Login into iLO Amplifier Pack and create a session try: REDFISH_OBJ.login(auth="session") except: print("Invalid iLO Amplifier Pack credential\n") exit() updateServerList = list(dict.fromkeys(args.ServerAddress))
import sys import redfish # When running on the server locally use the following commented values # iLO_host = "blobstore://." # iLO_account = "None" # iLO_password = "******" # When running remotely connect using the iLO address, iLO account name, # and password to send https requests iLO_host = "https://10.0.0.100" login_account = "admin" login_password = "******" ## Create a REDFISH object REDFISH_OBJ = redfish.redfish_client(base_url=iLO_host,username=login_account, \ password=login_password, default_prefix='/redfish/v1') # Login into the server and create a session REDFISH_OBJ.login(auth="session") # Do a GET on a given path response = REDFISH_OBJ.get("/redfish/v1/systems/1", None) # Print out the response sys.stdout.write("%s\n" % response) # Logout of the current session REDFISH_OBJ.logout()