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 get_power_state(ip, login_account, login_password, system_id): """Get power state :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 state 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 # GET the ComputerSystem resource power_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 power_state = {} # Get the PowerState property PowerState = response_system_url.dict["PowerState"] power_state["PowerState"] = PowerState power_details.append(power_state) 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'] = power_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
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
# Connect using the address, account name, and password login_host = "https://10.243.13.101" login_account = "USERID" login_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") # GET the ComputerSystem resource system_url = utils.get_system_url("/redfish/v1", REDFISH_OBJ) response_system_url = REDFISH_OBJ.get(system_url, None) # Print out the system information sys.stdout.write("\n") sys.stdout.write("Manufacturer : %s\n" % response_system_url.dict["Manufacturer"]) sys.stdout.write("Model : %s\n" % response_system_url.dict["Model"]) sys.stdout.write("SKU Number : %s\n" % response_system_url.dict["SKU"]) sys.stdout.write("Serial Number : %s\n" % response_system_url.dict["SerialNumber"]) sys.stdout.write("Asset Tag : %s\n" % response_system_url.dict["AssetTag"]) sys.stdout.write("System UUID : %s\n" % response_system_url.dict["UUID"]) sys.stdout.write("Host Name : %s\n" % response_system_url.dict["HostName"]) sys.stdout.write("Procesors Model : %s\n" % response_system_url.dict["ProcessorSummary"]["Model"]) sys.stdout.write("Procesors Count : %s\n" % response_system_url.dict["ProcessorSummary"]["Count"]) sys.stdout.write("Total Memory : %s GB\n" % response_system_url.dict["MemorySummary"]["TotalSystemMemoryGiB"]) sys.stdout.write("BIOS Version : %s\n" % response_system_url.dict["BiosVersion"])
def get_memory_inventory(ip, login_account, login_password, system_id, member_id): """Get memory 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 :params member_id: Memory member id :type member_id: None or int :returns: returns memory 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') # 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" } return result system_details = [] # GET the ComputerSystem resource try: 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" } return result list_memory_info = [] 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: memroys_url = response_system_url.dict["Memory"]["@odata.id"] response_memory_url = REDFISH_OBJ.get(memroys_url, None) if response_memory_url.status == 200: list_memory_url = response_memory_url.dict["Members"] # check member_id validity if member_id != None: if member_id <= 0 or member_id > len(list_memory_url): result = { 'ret': False, 'msg': "Specified member id is not valid. The id should be within 1~%s" % (len(list_memory_url)) } REDFISH_OBJ.logout() return result # get each memory info index = 1 for memory_dict in list_memory_url: if member_id != None and index != member_id: index = index + 1 continue index = index + 1 sub_memory_url = memory_dict["@odata.id"] response_sub_memory_url = REDFISH_OBJ.get( sub_memory_url, None) if response_sub_memory_url.status == 200: memory_info = {} if response_sub_memory_url.dict["Status"][ "State"] == "Absent": memory_info[ "Status"] = response_sub_memory_url.dict[ "Status"] memory_info[ "MemoryLocation"] = response_sub_memory_url.dict[ "MemoryLocation"] memory_info[ "Id"] = response_sub_memory_url.dict["Id"] list_memory_info.append(memory_info) continue for key in response_sub_memory_url.dict: if key == "Links" or key.startswith( "@") or key == "Oem": continue else: memory_info[ key] = response_sub_memory_url.dict[ key] list_memory_info.append(memory_info) else: error_message = utils.get_extended_error( response_sub_memory_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (sub_memory_url, response_sub_memory_url.status, error_message) } return result else: error_message = utils.get_extended_error( response_memory_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\n error_message: %s" % (memroys_url, response_memory_url.status, error_message) } return result else: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\n error_message: %s" % (system_url, response_system_url.status, error_message) } return result result['ret'] = True result['entries'] = list_memory_info return result except Exception as e: result = {'ret': False, 'msg': "exception msg %s" % e} return result finally: REDFISH_OBJ.logout()
def set_bios_password(ip, login_account, login_password, system_id, bios_password_name, bios_password, oldbiospass): """Set Bios password :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 bios_password_name: Bios password name by user specified :type bios_password_name: string :params bios_password: Bios password by user specified :type bios_password: string :params oldbiospass: Old Bios password :type oldbiospass: None or string :returns: returns set bios password 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', 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 try: # 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" } 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 ComputerBios resource if len(system) > 1 and 'Bios' not in response_system_url.dict: continue bios_url = response_system_url.dict['Bios']['@odata.id'] else: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: # Get password name allowable value list attribute_registry = response_bios_url.dict[ 'AttributeRegistry'] registry_url = "/redfish/v1/Registries" bios_registry_url = "" registry_response = REDFISH_OBJ.get(registry_url, None) if registry_response.status == 200: members_list = registry_response.dict["Members"] for registry in members_list: if attribute_registry in registry["@odata.id"]: bios_registry_url = registry["@odata.id"] bios_registry_json_url = "" if bios_registry_url != "": bios_registry_response = REDFISH_OBJ.get( bios_registry_url, None) if bios_registry_response.status == 200: bios_registry_json_url = bios_registry_response.dict[ "Location"][0]["Uri"] bios_attribute_list = [] if bios_registry_json_url != "": bios_registry_json_response = REDFISH_OBJ.get( bios_registry_json_url, None) if bios_registry_json_response.status == 200: bios_attribute_list = bios_registry_json_response.dict[ "RegistryEntries"]["Attributes"] password_allowed_values = [] for bios_attribute in bios_attribute_list: AttributeName = bios_attribute["AttributeName"] AttributeType = bios_attribute["Type"] if AttributeType == "Password": password_allowed_values.append(AttributeName) if len(password_allowed_values) == 0: if "*****@*****.**" in response_bios_url.dict[ "Actions"]["#Bios.ChangePassword"]: password_allowed_values = response_bios_url.dict[ "Actions"]["#Bios.ChangePassword"][ "*****@*****.**"] # Check whether password name is in allowable value list if len( password_allowed_values ) != 0 and bios_password_name not in password_allowed_values: result = { 'ret': False, 'msg': "Specified password name is not included in allowable value list. Please select password name from list: %s" % (str(password_allowed_values)) } return result # get parameter requirement if ActionInfo is provided if "@Redfish.ActionInfo" in response_bios_url.dict["Actions"][ "#Bios.ChangePassword"]: actioninfo_url = response_bios_url.dict["Actions"][ "#Bios.ChangePassword"]["@Redfish.ActionInfo"] response_actioninfo_url = REDFISH_OBJ.get( actioninfo_url, None) if (response_actioninfo_url.status == 200) and ("Parameters" in response_actioninfo_url.dict): for parameter in response_actioninfo_url.dict[ "Parameters"]: if ("OldPassword" == parameter["Name"]) and ( True == parameter["Required"]): if oldbiospass == None: result = { 'ret': False, 'msg': "Required parameter oldbiospasswd need to be specified." } return result # Get the change password url change_password_url = response_bios_url.dict['Actions'][ '#Bios.ChangePassword']['target'] # Set Password info requestbody = {} PasswordName = bios_password_name new_password = bios_password if oldbiospass == None: requestbody = { "PasswordName": PasswordName, "NewPassword": new_password } else: requestbody = { "PasswordName": PasswordName, "NewPassword": new_password, "OldPassword": oldbiospass } # Change password response_change_password = REDFISH_OBJ.post( change_password_url, body=requestbody) if response_change_password.status in [200, 204]: result = { 'ret': True, 'msg': 'Setting BIOS password successfully' } # Note: For SR635 and SR655 servers, if new password not meet BIOS password policy requirement, # redfish API may fail to identify errors and return success. In this case, # new BIOS password is not set in server, you should use original BIOS password. else: error_message = utils.get_extended_error( response_change_password) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (change_password_url, response_change_password.status, error_message) } return result else: error_message = utils.get_extended_error(response_bios_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message) } return result except Exception as e: result = {'ret': False, 'msg': "error_message: %s" % (e)} finally: # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def get_cpu_info(ip, login_account, login_password, system_id): """Get cpu 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 cpu 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') # 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" } return result cpu_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)): # Get Processors url system_url = system[i] response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status == 200: processors_url = response_system_url.dict['Processors'][ '@odata.id'] else: result = { 'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result # Get the Processors collection response_processors_url = REDFISH_OBJ.get(processors_url, None) if response_processors_url.status == 200: # Get Members url members_count = response_processors_url.dict['*****@*****.**'] else: result = { 'ret': False, 'msg': "response_processors_url Error code %s" % response_processors_url.status } REDFISH_OBJ.logout() return result # Get each processor info for i in range(members_count): cpu = {} # Get members url resource members_url = response_processors_url.dict['Members'][i][ '@odata.id'] response_members_url = REDFISH_OBJ.get(members_url, None) if response_members_url.status == 200: for property in [ 'Id', 'Name', 'TotalThreads', 'InstructionSet', 'Status', 'ProcessorType', 'TotalCores', 'Manufacturer', 'MaxSpeedMHz', 'Model', 'Socket' ]: if property in response_members_url.dict: cpu[property] = response_members_url.dict[property] cpu_details.append(cpu) else: result = { 'ret': False, 'msg': "response_members_url Error code %s" % response_members_url.status } result['ret'] = True result['entries'] = cpu_details # Logout of the current session REDFISH_OBJ.logout() return result
def get_system_info(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, 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"} return result 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 Host_Name = response_system_url.dict["HostName"] Model = response_system_url.dict["Model"] SerialNumber = response_system_url.dict["SerialNumber"] AssetTag = response_system_url.dict["AssetTag"] UUID = response_system_url.dict["UUID"] Procesors_Model = response_system_url.dict["ProcessorSummary"]["Model"] ProcesorsCount = response_system_url.dict["ProcessorSummary"]["Count"] Total_Memory = response_system_url.dict["MemorySummary"]["TotalSystemMemoryGiB"] BIOS_Version = response_system_url.dict["BiosVersion"] system['HostName'] = Host_Name system['Model'] = Model system['SerialNumber'] = SerialNumber system['AssetTag'] = AssetTag system['UUID'] = UUID system['Procesors_Model'] = Procesors_Model system['ProcesorsCount'] = ProcesorsCount system['TotalSystemMemoryGiB'] = Total_Memory system['BiosVersion'] = BIOS_Version system_details.append(system) # 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 for x in range(0, nic_count): ethernetinterface = [] 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: PermanentMACAddress = response_nic_x_url.dict["PermanentMACAddress"] EtherNetInterfaces['PermanentMACAddress'] = PermanentMACAddress ethernetinterface.append(EtherNetInterfaces) system['EtherNetInterfaces'] = ethernetinterface else: result = {'ret': False, 'msg': "response nic_x_url Error code %s" % response_nic_x_url.status} REDFISH_OBJ.logout() return result 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 REDFISH_OBJ.logout() return result
def lenovo_generate_snmp_engineid(ip, login_account, login_password, system_id): """Generate SNMP engine id :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 generated SNMP engine id 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 # 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 sub_model = None serial_number = None host_name = None for i in range(len(system)): request_url = system[i] 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 if 'SubModel' in response_url.dict: sub_model = response_url.dict['SubModel'] if 'SerialNumber' in response_url.dict: serial_number = response_url.dict['SerialNumber'] if 'HostName' in response_url.dict: host_name = response_url.dict['HostName'] engine_id_string = "" if sub_model is not None and serial_number is not None: engine_id_string = "XCC-%s-%s" % (sub_model, serial_number) elif host_name is not None: engine_id_string = "%s" % (host_name) else: result = { 'ret': False, 'msg': "Failed to get necessary information from ComputeSystem for SNMP engine id generating." } REDFISH_OBJ.logout() return result engine_id_hexstr = "80 00 1F 88 04" for char in engine_id_string: engine_id_hexstr = engine_id_hexstr + ' %2X' % (ord(char)) result['ret'] = True result['data'] = engine_id_hexstr # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def get_all_bios_attributes(ip, login_account, login_password, system_id, bios_get): """Get all bios attribute :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 bios_get: current setting or pending setting(default is current) :type bios_get: string :returns: returns all bios attribute when succeeded or error message when failed """ result = {} try: # Connect using the BMC address, account name, and password # Create a REDFISH object login_host = "https://" + ip 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 try: # 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 attributes = [] 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 current url bios_url = response_system_url.dict['Bios']['@odata.id'] else: result = { 'ret': False, 'msg': "response system url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: if bios_get == "current": # Get the bios url resource attribute = response_bios_url.dict['Attributes'] attributes.append(attribute) elif bios_get == "pending": # Get pending url pending_url = response_bios_url.dict['@Redfish.Settings'][ 'SettingsObject']['@odata.id'] response_pending_url = REDFISH_OBJ.get(pending_url, None) if response_pending_url.status == 200: # Get the pending url resource pending_attribute = response_pending_url.dict[ 'Attributes'] current_attribute = response_bios_url.dict[ 'Attributes'] changed_attribute = {} for key in pending_attribute: if pending_attribute[key] != current_attribute[key]: changed_attribute[key] = pending_attribute[key] attributes.append(changed_attribute) else: error_message = utils.get_extended_error( response_pending_url) result = { 'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % (pending_url, response_pending_url.status, error_message) } return result else: result = { 'ret': False, 'msg': "Please input '--bios current' or '--bios pending'" } return result else: error_message = utils.get_extended_error(response_bios_url) result = { 'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message) } return result result['ret'] = True result['attributes'] = attributes except Exception as e: result = {'ret': False, 'msg': "error message %s" % e} finally: # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def set_server_boot_once(ip, login_account, login_password, system_id, boot_source, mode): """Set server boot once :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 boot_source: Boot source type by user specified :type boot_source: string :params mode: Boot mode :type mode: string :returns: returns set server boot once result when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the 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() sys.stdout.write( "Please check the username, password, IP is correct\n") sys.exit(1) try: # 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] # get etag to set If-Match precondition response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status != 200: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' get failed. response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result if "@odata.etag" in response_system_url.dict: etag = response_system_url.dict['@odata.etag'] else: etag = "" headers = {"If-Match": etag} # Prepare PATCH Body to set Boot once to the user specified target patch_body = { "Boot": { "BootSourceOverrideEnabled": "", "BootSourceOverrideTarget": "" } } if boot_source == "None": patch_body["Boot"]["BootSourceOverrideEnabled"] = "Disabled" else: patch_body["Boot"]["BootSourceOverrideEnabled"] = "Once" patch_body["Boot"]["BootSourceOverrideTarget"] = boot_source if mode: patch_body["Boot"]["BootSourceOverrideMode"] = mode patch_response = REDFISH_OBJ.patch(system_url, body=patch_body, headers=headers) # If Response does not return 200/OK or 204, print the response Extended Error message if patch_response.status in [200, 204]: result = { 'ret': True, 'msg': "Set server boot once '%s' successfully" % boot_source } else: message = utils.get_extended_error(patch_response) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \n, Error message :%s" % (system_url, patch_response.status, message) } except Exception as e: traceback.print_exc() result = {'ret': False, 'msg': "error_message: %s" % (e)} finally: # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def get_storage_info(ip, login_account, login_passwprd, system_id): """Get storage 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 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') # 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" } 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 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 Storage resources from the ComputerSystem resource if "Storage" in response_system_url.dict: storage_url = response_system_url.dict["Storage"]["@odata.id"] else: storage_url = response_system_url.dict["SimpleStorage"][ "@odata.id"] response_storage_url = REDFISH_OBJ.get(storage_url, None) if response_storage_url.status == 200: storage_count = response_storage_url.dict[ "*****@*****.**"] storage = 0 for nic in range(0, storage_count): storage_x_url = response_storage_url.dict["Members"][nic][ "@odata.id"] response_storage_x_url = REDFISH_OBJ.get( storage_x_url, None) if response_storage_x_url.status == 200: storage = {} Storage_id = response_storage_x_url.dict["Id"] Name = response_storage_x_url.dict["Name"] storage['Id'] = Storage_id storage['Name'] = Name if "Devices" in response_storage_x_url.dict: Devices_list = response_storage_x_url.dict[ 'Devices'] for storage_info in Devices_list: Manufacturer = storage_info['Manufacturer'] Model = storage_info['Model'] CapacityBytes = storage_info['CapacityBytes'] Devies_Name = storage_info['Name'] storage['Manufacturer'] = Manufacturer storage['Model'] = Model storage['CapacityBytes'] = CapacityBytes storage['Devies_Name'] = Devies_Name storage_details.append(storage) continue controller_count = response_storage_x_url.dict[ "*****@*****.**"] controller = 0 # GET the StorageControllers instances resources from each of the Storage resources storage_list = [] for controller in range(0, controller_count): storage_controller = {} Controller = controller Manufacturer = response_storage_x_url.dict[ "StorageControllers"][controller][ "Manufacturer"] Model = response_storage_x_url.dict[ "StorageControllers"][controller]["Model"] SerialNumber = response_storage_x_url.dict[ "StorageControllers"][controller][ "SerialNumber"] FirmwareVersion = response_storage_x_url.dict[ "StorageControllers"][controller][ "FirmwareVersion"] PartNumber = response_storage_x_url.dict[ "StorageControllers"][controller]["PartNumber"] DurableNameFormat = response_storage_x_url.dict[ "StorageControllers"][controller][ "Identifiers"][0]["DurableNameFormat"] DurableName = response_storage_x_url.dict[ "StorageControllers"][controller][ "Identifiers"][0]["DurableName"] storage_controller[Manufacturer] = Manufacturer storage_controller["Model"] = Model storage_controller["SerialNumber"] = SerialNumber storage_controller[ "FirmwareVersion"] = FirmwareVersion storage_controller["PartNumber"] = PartNumber storage_controller[ "DurableNameFormat"] = DurableNameFormat storage_controller["DurableName"] = DurableName storage_list.append(storage_controller) storage['torage_controller'] = storage_list storage_details.append(storage) else: result = { 'ret': False, 'msg': "response_storage_x_url code %s" % response_storage_x_url.status } REDFISH_OBJ.logout() return result else: result = { 'ret': False, 'msg': "response storage url Error code %s" % response_storage_url.status } REDFISH_OBJ.logout() 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'] = storage_details # Logout of the current session REDFISH_OBJ.logout() return result
def set_bios_bootmode_legacy(ip, login_account, login_password, system_id): """Get set bios bootmode legacy result :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 set bios bootmode legacy 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" } 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] attributes = {} attributes['bios_attr_name'] = "BootSourceOverrideMode" attributes['bios_attr_value'] = "Legacy" bios_attributes = "{\"" + attributes[ 'bios_attr_name'] + "\":\"" + attributes['bios_attr_value'] + "\"}" parameter = {"Boot": json.loads(bios_attributes)} response_system_url = REDFISH_OBJ.patch(system_url, body=parameter) if response_system_url.status in [200, 204]: result = { 'ret': True, 'msg': 'set bios bootmode legacy successful' } elif response_system_url.status == 400: result = {'ret': False, 'msg': 'Not supported on this platform'} elif response_system_url.status == 405: result = {'ret': False, 'msg': "Resource not supported"} else: result = {'ret': False, 'msg': "set bios bootmode legacy failed"} # Logout of the current session REDFISH_OBJ.logout() return result
def get_bios_attribute_metadata(ip, login_account, login_password, system_id): """Get bios attribute metadata :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 bios attribute metadata 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" } 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 ComputerBios resource bios_url = response_system_url.dict['Bios']['@odata.id'] else: result = { 'ret': False, 'msg': "response system url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: metadata_url = response_bios_url.dict['@odata.context'] result = {'ret': True, 'msg': "Metadata_url %s" % metadata_url} elif response_bios_url.status_code == 400: result = {'ret': False, 'msg': 'Not supported on this platform'} else: result = { 'ret': False, 'msg': "response bios url Error code %s" % response_bios_url.status } REDFISH_OBJ.logout() return result result['ret'] = True # Logout of the current session REDFISH_OBJ.logout() return result
def set_bios_attribute(ip, login_account, login_password, system_id, attribute_name, attribute_value): """Set Bios attribute :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 attribute_name: Bios attribute name by user specified :type attribute_name: string :params attribute_value: Bios attribute value by user specified :type attribute_value: string :returns: returns set bios attribute 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, 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 try: # 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 ComputerBios resource bios_url = response_system_url.dict['Bios']['@odata.id'] else: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result # Get bios url resource response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: if "SettingsObject" in response_bios_url.dict[ '@Redfish.Settings'].keys(): pending_url = response_bios_url.dict['@Redfish.Settings'][ 'SettingsObject']['@odata.id'] else: pending_url = bios_url + "/SD" attribute_registry = response_bios_url.dict[ 'AttributeRegistry'] else: error_message = utils.get_extended_error(response_bios_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message) } return result registry_url = "/redfish/v1/Registries" registry_response = REDFISH_OBJ.get(registry_url, None) if registry_response.status == 200: members_list = registry_response.dict["Members"] for registry in members_list: if attribute_registry in registry["@odata.id"]: bios_registry_url = registry["@odata.id"] else: error_message = utils.get_extended_error(registry_response) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (registry_url, registry_response.status, error_message) } return result bios_registry_response = REDFISH_OBJ.get(bios_registry_url, None) if bios_registry_response.status == 200: bios_registry_json_url = bios_registry_response.dict[ "Location"][0]["Uri"] else: error_message = utils.get_extended_error( bios_registry_response) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_registry_url, bios_registry_response.status, error_message) } return result bios_registry_json_response = REDFISH_OBJ.get( bios_registry_json_url, None) if bios_registry_json_response.status == 200: bios_attribute_list = bios_registry_json_response.dict[ "RegistryEntries"]["Attributes"] else: error_message = utils.get_extended_error( bios_registry_json_response) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_registry_json_url, bios_registry_json_response.status, error_message) } return result parameter = {} for bios_attribute in bios_attribute_list: AttributeName = bios_attribute["AttributeName"] AttributeType = bios_attribute["Type"] if attribute_name == AttributeName: if AttributeType == "Integer": try: attribute_value = int(attribute_value) parameter = {attribute_name: attribute_value} except: result = { 'ret': False, 'msg': "Please check the attribute value, this should be a number." } return result elif AttributeType == "Boolean": if attribute_value.upper() == "TRUE": parameter = {attribute_name: True} elif attribute_value.upper() == "FALSE": parameter = {attribute_name: False} else: result = { 'ret': False, 'msg': "Please check the attribute value, this value is 'true' or 'false'." } return result else: parameter = {attribute_name: attribute_value} break else: continue if parameter: attribute = {"Attributes": parameter} else: result = { "ret": False, "msg": "This bios attribute '%s' not supported on this platform" % attribute_name } return result headers = {"If-Match": "*", "Content-Type": "application/json"} response_pending_url = REDFISH_OBJ.patch(pending_url, headers=headers, body=attribute) if response_pending_url.status in [200, 204]: result = { 'ret': True, 'msg': '%s set Successful' % attribute_name } elif response_pending_url.status == 400: result = { 'ret': False, 'msg': 'Not supported on this platform' } elif response_pending_url.status == 405: result = {'ret': False, 'msg': "Resource not supported"} else: error_message = utils.get_extended_error(response_pending_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (pending_url, response_pending_url.status, error_message) } return result except Exception as e: traceback.print_exc() result = {'ret': False, 'msg': "error_message: %s" % (e)} finally: # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def get_system_reset_types(ip, login_account, login_password, system_id): """Get reset types :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 reset types 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 reset_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: # check whether Reset is supported if ("Actions" not in response_system_url.dict) or ( "#ComputerSystem.Reset" not in response_system_url.dict["Actions"]): result = { 'ret': False, 'msg': "Reset action is not supported." } REDFISH_OBJ.logout() return result # get AllowableValues for Reset action reset_types = {} if "*****@*****.**" in response_system_url.dict[ "Actions"]["#ComputerSystem.Reset"]: Computer_reset = response_system_url.dict["Actions"][ "#ComputerSystem.Reset"][ "*****@*****.**"] reset_types[ "*****@*****.**"] = Computer_reset reset_details.append(reset_types) elif "@Redfish.ActionInfo" in response_system_url.dict["Actions"][ "#ComputerSystem.Reset"]: actioninfo_url = response_system_url.dict["Actions"][ "#ComputerSystem.Reset"]["@Redfish.ActionInfo"] response_actioninfo_url = REDFISH_OBJ.get(actioninfo_url, None) if response_actioninfo_url.status == 200: if "Parameters" in response_actioninfo_url.dict: for parameter in response_actioninfo_url.dict[ "Parameters"]: if ("Name" in parameter) and (parameter["Name"] == "ResetType"): if "AllowableValues" in parameter: reset_types[ "*****@*****.**"] = parameter[ "AllowableValues"] reset_details.append(reset_types) else: result = { 'ret': False, 'msg': "Get url %s failed. Error code %s" % (actioninfo_url, response_actioninfo_url.status) } REDFISH_OBJ.logout() return result if "*****@*****.**" not in reset_types: result = { 'ret': False, 'msg': "No AllowableValues information found for Reset action." } REDFISH_OBJ.logout() return result 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'] = reset_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def set_reset_system(ip, login_account, login_password, system_id, reset_type): """Reset system :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 reset_type: reset system type by user specified :type reset_type: string :returns: returns reset system type result when succeeded or error message when failed """ result = {} login_host = "https://" + ip try: # Connect using the 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: sys.stdout.write( "Please check the username, password, IP is correct\n") sys.exit(1) try: # 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] # GET the ComputerSystem resource response_system_url = REDFISH_OBJ.get(system_url, None) if response_system_url.status == 200: # Find the Reset Action target URL target_url = response_system_url.dict["Actions"][ "#ComputerSystem.Reset"]["target"] # Prepare POST body post_body = {"ResetType": reset_type} # POST Reset Action post_response = REDFISH_OBJ.post(target_url, body=post_body) # If Response return 200/OK, return successful , else print the response Error code if post_response.status in [200, 204]: result = { 'ret': True, 'msg': "reset system '%s' successful" % reset_type } else: error_message = utils.get_extended_error(post_response) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (target_url, post_response.status, error_message) } return result else: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result except Exception as e: result = {'ret': False, 'msg': "error_message: %s" % e} finally: # Logout of the current session REDFISH_OBJ.logout() return result
def get_psu_info(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, 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" } 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', 'PartNumber', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status', 'Manufacturer' ]: if property in PowerSupplies: entry[property] = PowerSupplies[property] 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 REDFISH_OBJ.logout() return result
def get_secure_boot_status(ip, login_account, login_password, system_id): """Get secure boot status :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 secure boot status 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 # GET the ComputerSystem resource secure_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: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } REDFISH_OBJ.logout() return result if 'SecureBoot' not in response_system_url.dict: continue secure_boot_url = response_system_url.dict['SecureBoot']['@odata.id'] # Get the secure boot url resource response_secure_boot_url = REDFISH_OBJ.get(secure_boot_url, None) if response_secure_boot_url.status == 200: secure = {} secure_boot_enable = response_secure_boot_url.dict[ "SecureBootEnable"] secure_boot_mode = response_secure_boot_url.dict["SecureBootMode"] secure['SecureBootEnable'] = secure_boot_enable secure['SecureBootMode'] = secure_boot_mode secure_details.append(secure) else: error_message = utils.get_extended_error(response_secure_boot_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (secure_boot_url, response_secure_boot_url.status, error_message) } REDFISH_OBJ.logout() return result if len(secure_details) == 0: result = {'ret': False, 'msg': "Not support SecureBoot"} else: result['ret'] = True result['entries'] = secure_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def lenovo_set_bios_boot_order(ip, login_account, login_password, system_id, bootorder): """set bios boot order :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 bootorder: Specify the bios boot order list, The boot order takes effect on the next startup :type bootorder: list :returns: returns set bios boot order 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, 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 try: # 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" } 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: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result # Set boot order via Oem/Lenovo/BootSettings resource for ThinkSystem servers except SR635/SR655 if 'Lenovo' in str( response_system_url.dict) and 'BootSettings' in str( response_system_url.dict): # Get the BootSettings url boot_settings_url = response_system_url.dict['Oem']['Lenovo'][ 'BootSettings']['@odata.id'] # Get the boot order settings url from boot settings resource response_boot_settings = REDFISH_OBJ.get( boot_settings_url, None) if response_boot_settings.status == 200: boot_order_url = response_boot_settings.dict['Members'][0][ '@odata.id'] else: error_message = utils.get_extended_error( response_boot_settings) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (boot_settings_url, response_boot_settings.status, error_message) } return result # Get the boot order supported list response_get_boot_order = REDFISH_OBJ.get(boot_order_url, None) if response_get_boot_order.status == 200: boot_order_supported = response_get_boot_order.dict[ 'BootOrderSupported'] for boot in bootorder: if boot not in boot_order_supported: result = { 'ret': False, 'msg': "Invalid bootorder %s. You can specify one or more boot order form list:%s" % (boot, boot_order_supported) } return result # Set the boot order next via patch request body = {"BootOrderNext": bootorder} response_boot_order = REDFISH_OBJ.patch(boot_order_url, body=body) if response_boot_order.status == 200: boot_order_next = response_boot_order.dict["BootOrderNext"] result = { 'ret': True, 'msg': "Modified Boot Order '%s' successfully. New boot order will take effect on the next startup." % (boot_order_next) } return result else: error_message = utils.get_extended_error( response_boot_order) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (boot_order_url, response_boot_order.status, error_message) } return result # Set boot order via Bios Q00999_Boot_Option_Priorities attribute resource for ThinkSystem SR635/SR655 if 'SR635' in str(response_system_url.dict) or 'SR655' in str( response_system_url.dict): # Get /redfish/v1/Systems/Self/Bios resource bios_url = response_system_url.dict['Bios']['@odata.id'] response_bios = REDFISH_OBJ.get(bios_url, None) if response_bios.status != 200: error_message = utils.get_extended_error(response_bios) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios.status, error_message) } return result # Get current boot order setting from specified attribute attribute_name = 'Q00999_Boot_Option_Priorities' attribute_value = '' if 'Q00999_Boot_Option_Priorities' in response_bios.dict[ 'Attributes']: attribute_name = 'Q00999_Boot_Option_Priorities' attribute_value = response_bios.dict['Attributes'][ attribute_name] elif 'Q00999 Boot Option Priorities' in response_bios.dict[ 'Attributes']: attribute_name = 'Q00999 Boot Option Priorities' attribute_value = response_bios.dict['Attributes'][ attribute_name] else: continue # Get supported boot order list boot_order_supported = list() org_boot_order_struct_list = attribute_value.split(';') for boot_order_struct in org_boot_order_struct_list: boot_order_name = boot_order_struct.split(',')[0] boot_order_supported.append(boot_order_name) # Set payload body body = {} new_boot_order_struct_list = list() for boot in bootorder: # If input bootorder is not supported, prompt error message if boot not in boot_order_supported: result = { 'ret': False, 'msg': "Invalid bootorder %s. You can specify one or more boot order form list:%s" % (boot, boot_order_supported) } return result # Add enabled bootorder list for boot_order_struct in org_boot_order_struct_list: boot_order_name = boot_order_struct.split(',')[0] if boot == boot_order_name: newstruct = boot_order_struct.replace( 'false', 'true') if newstruct not in new_boot_order_struct_list: new_boot_order_struct_list.append(newstruct) # Add disabled bootorder list for boot_order_struct in org_boot_order_struct_list: boot_order_name = boot_order_struct.split(',')[0] if boot_order_name not in bootorder: newstruct = boot_order_struct.replace('true', 'false') if newstruct not in new_boot_order_struct_list: new_boot_order_struct_list.append(newstruct) new_boot_order_struct_string = '' for item in new_boot_order_struct_list: new_boot_order_struct_string = new_boot_order_struct_string + item + ';' body = { "Attributes": { attribute_name: new_boot_order_struct_string } } headers = {"If-Match": '*'} # Set the boot order via patch request bios_settings_url = response_bios.dict['@Redfish.Settings'][ 'SettingsObject']['@odata.id'] response_bios_settings = REDFISH_OBJ.patch(bios_settings_url, body=body, headers=headers) if response_bios_settings.status in [200, 204]: result = { 'ret': True, 'msg': "Modified Boot Order successfully. New boot order will take effect on the next startup." } return result else: error_message = utils.get_extended_error( response_bios_settings) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_settings_url, response_bios_settings.status, error_message) } return result result = { 'ret': False, 'msg': "No related resource found, fail to set bios boot order for target server." } return result except Exception as e: traceback.print_exc() result = {'ret': False, 'msg': "error_message:%s" % (e)} finally: # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def get_bios_attribute(ip, login_account, login_password, system_id, attribute_name): """get bios attribute by user specified :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 attribute_name: Bios attribute name by user specified :type attribute_name: string :returns: returns get bios attribute value when succeeded or error message when failed """ result = {} try: # Connect using the BMC address, account name, and password # Create a REDFISH object login_host = "https://" + ip 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" } return result try: # 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" } 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 ComputerBios resource bios_url = response_system_url.dict['Bios']['@odata.id'] else: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: attribute = response_bios_url.dict['Attributes'] bios_attribute = {} if attribute_name in attribute.keys(): bios_attribute[attribute_name] = attribute[attribute_name] result = {'ret': True, 'msg': bios_attribute} else: result = { 'ret': False, 'msg': " No this attribute in the bios attribute" } elif response_bios_url.status == 400: result = { 'ret': False, 'msg': 'Not supported on this platform' } REDFISH_OBJ.logout() return result else: error_message = utils.get_extended_error(response_bios_url) result = { 'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message) } return result except Exception as e: result = {'ret': False, 'msg': "error message %s" % e} finally: # Logout of the current session REDFISH_OBJ.logout() return result
def enable_secure_boot(ip, login_account, login_password, system_id): """Enable secure boot :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 enable secure boot 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 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 secureboot_url = response_system_url.dict['SecureBoot'][ '@odata.id'] secure_boot_enable = True parameter = {"SecureBootEnable": secure_boot_enable} response_secureboot = REDFISH_OBJ.patch(secureboot_url, body=parameter) if response_secureboot.status == 200: result = { 'ret': True, 'msg': "PATCH command successfully completed \"%s\" request for enable secure boot" % secure_boot_enable } else: result = { 'ret': False, 'msg': "response secureboot Error code %s" % response_secureboot.status } REDFISH_OBJ.logout() return result else: result = { 'ret': False, 'msg': "response system url Error code %s" % response_system_url.status } REDFISH_OBJ.logout() return result
def get_storage_inventory(ip, login_account, login_password, system_id): """Get storage 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 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, 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 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 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 Storage resources from the ComputerSystem resource if "Storage" in response_system_url.dict: storage_url = response_system_url.dict["Storage"]["@odata.id"] else: storage_url = response_system_url.dict["SimpleStorage"][ "@odata.id"] response_storage_url = REDFISH_OBJ.get(storage_url, None) if response_storage_url.status == 200: storage_count = len(response_storage_url.dict["Members"]) storage = 0 for nic in range(0, storage_count): storage_x_url = response_storage_url.dict["Members"][nic][ "@odata.id"] response_storage_x_url = REDFISH_OBJ.get( storage_x_url, None) if response_storage_x_url.status == 200: storage = {} Storage_id = response_storage_x_url.dict["Id"] Name = response_storage_x_url.dict["Name"] storage['Id'] = Storage_id storage['Name'] = Name # Get the disk inventory from each of the disk resources drive_list = [] if "Drives" in response_storage_x_url.dict: for disk in response_storage_x_url.dict["Drives"]: disk_inventory = {} disk_url = disk["@odata.id"] response_disk_url = REDFISH_OBJ.get( disk_url, None) if response_disk_url.status == 200: for key in response_disk_url.dict: if key not in [ "Description", "@odata.context", "@odata.id", "@odata.type", "@odata.etag", "Links", "Actions", "RelatedItem" ]: disk_inventory[ key] = response_disk_url.dict[ key] drive_list.append(disk_inventory) else: error_message = utils.get_extended_error( response_disk_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (disk_url, response_disk_url.status, error_message) } return result storage['Drives'] = drive_list if "Volumes" in response_storage_x_url.dict: 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: volumes_list = [] for volume in response_volumes_url.dict[ "Members"]: volume_inventory = {} volume_url = volume["@odata.id"] response_volume_url = REDFISH_OBJ.get( volume_url, None) if response_volume_url.status == 200: for key in response_volume_url.dict: if key not in [ "Description", "@odata.context", "@odata.id", "@odata.type", "@odata.etag", "Links", "Actions", "RelatedItem" ]: volume_inventory[ key] = response_volume_url.dict[ key] volumes_list.append(volume_inventory) else: error_message = utils.get_extended_error( response_volume_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % (volume_url, response_volume_url.status, error_message) } return result else: 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 storage['Volumes'] = volumes_list controller_count = response_storage_x_url.dict[ "*****@*****.**"] # GET the StorageControllers instances resources from each of the Storage resources storage_list = [] for controller in range(0, controller_count): storage_controller = {} for key in response_storage_x_url.dict[ "StorageControllers"][controller]: if key not in [ "Description", "@odata.context", "@odata.id", "@odata.type", "@odata.etag", "Links", "Actions", "RelatedItem" ]: storage_controller[ key] = response_storage_x_url.dict[ "StorageControllers"][controller][ key] storage_list.append(storage_controller) storage['storage_controller'] = storage_list storage_details.append(storage) else: result = { 'ret': False, 'msg': "response_storage_x_url code %s" % response_storage_x_url.status } REDFISH_OBJ.logout() return result else: result = { 'ret': False, 'msg': "response storage url Error code %s" % response_storage_url.status } REDFISH_OBJ.logout() 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'] = storage_details # Logout of the current session try: REDFISH_OBJ.logout() except: pass return result
def disable_secure_boot(ip, login_account, login_password, system_id): """Disable secure boot :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 enable secure boot 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', 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\n"} 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: error_message = utils.get_extended_error(response_system_url) result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( system_url, response_system_url.status, error_message)} REDFISH_OBJ.logout() return result if 'SecureBoot' in response_system_url.dict: # Get the SecureBoot resource url secureboot_url = response_system_url.dict['SecureBoot']['@odata.id'] # get etag to set If-Match precondition response_secureboot_url = REDFISH_OBJ.get(secureboot_url, None) if response_secureboot_url.status != 200: error_message = utils.get_extended_error(response_secureboot_url) result = {'ret': False, 'msg': "Url '%s' get failed. response Error code %s \nerror_message: %s" % ( secureboot_url, response_secureboot_url.status, error_message)} return result if "@odata.etag" in response_secureboot_url.dict: etag = response_secureboot_url.dict['@odata.etag'] else: etag = "*" headers = {"If-Match": etag} # perform patch to Disable secure boot secure_boot_enable = False parameter = {"SecureBootEnable": secure_boot_enable} response_secureboot = REDFISH_OBJ.patch(secureboot_url, body=parameter, headers=headers) if response_secureboot.status in [200,204]: result = {'ret': True, 'msg': "PATCH command successfully completed. SecureBootEnable has been set to False, it will take effect after system reboot."} else: error_message = utils.get_extended_error(response_secureboot) result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( secureboot_url, response_secureboot.status, error_message)} REDFISH_OBJ.logout() return result result = {'ret': False, 'msg': "Not support SecureBoot"} REDFISH_OBJ.logout() return result
def get_network_info(ip, login_account, login_password, system_id): """Get nic 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 nic 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') # 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" } return result # Get ServiceRoot resource response_base_url = REDFISH_OBJ.get("/redfish/v1", None) if response_base_url.status == 200: chassis_url_list = response_base_url.dict['Chassis']['@odata.id'] else: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % ("/redfish/v1", response_base_url.status) } REDFISH_OBJ.logout() return result # Get Chassis collection response_chassis_url_list = REDFISH_OBJ.get(chassis_url_list, None) if response_chassis_url_list.status == 200: chassis_count = response_chassis_url_list.dict['*****@*****.**'] else: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (chassis_url_list, response_chassis_url_list.status) } REDFISH_OBJ.logout() return result nic_details = [] for count in range(chassis_count): # GET the Chassis resource chassis_url = response_chassis_url_list.dict['Members'][count][ '@odata.id'] response_chassis_url = REDFISH_OBJ.get(chassis_url, None) if response_chassis_url.status != 200: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (chassis_url, response_chassis_url.status) } REDFISH_OBJ.logout() return result # Skip this chassis if no NetworkAdapters found in it if "NetworkAdapters" not in response_chassis_url.dict: continue # GET the NetworkAdapters resource from the Chassis resource nic_adapter_url = response_chassis_url.dict["NetworkAdapters"][ "@odata.id"] response_nic_adapter_url = REDFISH_OBJ.get(nic_adapter_url, None) if response_nic_adapter_url.status == 200: nic_adapter_count = response_nic_adapter_url.dict[ "*****@*****.**"] else: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (nic_adapter_url, response_nic_adapter_url.status) } REDFISH_OBJ.logout() return result for nic in range(0, nic_adapter_count): network = {} nic_adapter_x_url = response_nic_adapter_url.dict["Members"][nic][ "@odata.id"] response_nic_adapter_x_url = REDFISH_OBJ.get( nic_adapter_x_url, None) if response_nic_adapter_x_url.status != 200: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (nic_adapter_x_url, response_nic_adapter_x_url.status) } REDFISH_OBJ.logout() return result for property in [ 'Id', 'Name', 'Status', 'Manufacturer', 'Model', 'PartNumber', 'SKU', 'SerialNumber' ]: if property in response_nic_adapter_x_url.dict: network[property] = response_nic_adapter_x_url.dict[ property] if "Controllers" not in response_nic_adapter_x_url.dict: continue # get Controller info including NetworkDeviceFunctions and assigned port in Controller controller_list = [] for controller in response_nic_adapter_x_url.dict["Controllers"]: nic_devices = [] controller_data = {} for property in [ 'FirmwarePackageVersion', 'ControllerCapabilities' ]: if property in controller: controller_data[property] = controller[property] # get the NetworkDeviceFunction resources if ("Links" not in controller) or ("NetworkDeviceFunctions" not in controller["Links"]): continue for devfun in controller["Links"]["NetworkDeviceFunctions"]: NIC_Devices = {} nic_dev_x_url = devfun["@odata.id"] response_nic_dev_x_url = REDFISH_OBJ.get( nic_dev_x_url, None) if response_nic_dev_x_url.status != 200: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (nic_dev_x_url, response_nic_dev_url.status) } REDFISH_OBJ.logout() return result for property in [ 'Id', 'Name', 'NetDevFuncType', 'DeviceEnabled', 'Ethernet', 'Status' ]: if property in response_nic_dev_x_url.dict: NIC_Devices[ property] = response_nic_dev_x_url.dict[ property] # GET the associated NetworkPort resource if "PhysicalPortAssignment" in response_nic_dev_x_url.dict: nic_port_x_url = response_nic_dev_x_url.dict[ "PhysicalPortAssignment"]["@odata.id"] response_nic_port_x_url = REDFISH_OBJ.get( nic_port_x_url, None) if response_nic_port_x_url.status == 200: Physical_Ports = {} for property in [ 'PhysicalPortNumber', 'Name', 'ActiveLinkTechnology', 'PortMaximumMTU', 'Status', 'LinkStatus' ]: if property in response_nic_port_x_url.dict: Physical_Ports[ property] = response_nic_port_x_url.dict[ property] NIC_Devices['physical_port'] = Physical_Ports else: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (nic_port_x_url, response_nic_port_x_url.status) } REDFISH_OBJ.logout() return result nic_devices.append(NIC_Devices) controller_data['NetworkDeviceFunctions'] = nic_devices controller_list.append(controller_data) network['Controllers'] = controller_list nic_details.append(network) # if no info got from chassis, get info from /redfish/v1/Systems/{ComputerSystemId}/EthernetInterfaces/{EthernetInterfaceId} if len(nic_details) == 0: # 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 EthernetInterfaces url if 'EthernetInterfaces' not in response_system_url.dict: continue else: nic_adapter_url = response_system_url.dict[ 'EthernetInterfaces']['@odata.id'] else: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (system_url, response_system_url.status) } REDFISH_OBJ.logout() return result response_nic_adapter_url = REDFISH_OBJ.get(nic_adapter_url, None) if response_nic_adapter_url.status == 200: nic_adapter_count = response_nic_adapter_url.dict[ "*****@*****.**"] else: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (nic_adapter_url, response_nic_adapter_url.status) } REDFISH_OBJ.logout() return result for nic in range(0, nic_adapter_count): network = {} nic_adapter_x_url = response_nic_adapter_url.dict["Members"][ nic]["@odata.id"] response_nic_adapter_x_url = REDFISH_OBJ.get( nic_adapter_x_url, None) if response_nic_adapter_x_url.status != 200: result = { 'ret': False, 'msg': "get url %s failed. Error code %s" % (nic_adapter_x_url, response_nic_adapter_x_url.status) } REDFISH_OBJ.logout() return result # Get the nic info for property in [ 'Id', 'Name', 'MACAddress', 'MTUSize', 'FQDN', 'AutoNeg', 'Status' ]: if property in response_nic_adapter_x_url.dict: network[property] = response_nic_adapter_x_url.dict[ property] nic_details.append(network) continue result['ret'] = True result['entries'] = nic_details # Logout of the current session REDFISH_OBJ.logout() return result
def set_bios_bootmode_uefi(ip, login_account, login_password, system_id): """Get set bios bootmode uefi result :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 set bios bootmode uefi 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', 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 # 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: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } REDFISH_OBJ.logout() return result else: # Get the bios resource bios_url = response_system_url.dict['Bios']['@odata.id'] response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status != 200: error_message = utils.get_extended_error(response_bios_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message) } REDFISH_OBJ.logout() return result else: # Get bios success # Seek boot mode from bios attributes attribute_bootmode = None attributes = response_bios_url.dict['Attributes'] for attribute in attributes: if attribute == "BootMode" or attribute == "SystemBootMode": attribute_bootmode = attribute break if attribute_bootmode == None: for attribute in attributes: if "SystemBootMode" in attribute: attribute_bootmode = attribute break if attribute_bootmode == None: for attribute in attributes: if "Boot" in attribute and "Mode" in attribute: attribute_bootmode = attribute break if attribute_bootmode == None: result = { 'ret': False, 'msg': "Can not found BootMode attribute in response of url %s" % (bios_url) } REDFISH_OBJ.logout() return result # Get boot mode setting guide from bios registry WarningText = None ValueName = None bios_registry_url = "/redfish/v1/Registries/" + response_bios_url.dict[ 'AttributeRegistry'] response_bios_registry_url = REDFISH_OBJ.get( bios_registry_url, None) if response_bios_registry_url.status == 200: locations = response_bios_registry_url.dict['Location'] bios_regjson_url = None for location in locations: if location['Language'] == 'en': bios_regjson_url = location['Uri'] break if bios_regjson_url: response_bios_regjson_url = REDFISH_OBJ.get( bios_regjson_url, None) if response_bios_regjson_url.status == 200: regattributes = response_bios_regjson_url.dict[ 'RegistryEntries']['Attributes'] for regattribute in regattributes: if regattribute[ 'AttributeName'] == attribute_bootmode: if 'WarningText' in regattribute: WarningText = regattribute[ 'WarningText'] for value in regattribute['Value']: if 'legacy' in value[ 'ValueName'].lower(): continue if 'uefi' in value['ValueName'].lower( ): ValueName = value['ValueName'] break ValueName = value['ValueName'] break # Perform patch to set if ValueName == None: ValueName = "UEFIMode" pending_url = response_bios_url.dict['@Redfish.Settings'][ 'SettingsObject']['@odata.id'] parameter = {attribute_bootmode: ValueName} attribute = {"Attributes": parameter} headers = {"If-Match": '*'} response_pending_url = REDFISH_OBJ.patch(pending_url, body=attribute, headers=headers) if response_pending_url.status in [200, 204]: if WarningText: result = { 'ret': True, 'msg': 'set bios bootmode uefi successful. WarningText: %s' % (WarningText) } else: result = { 'ret': True, 'msg': 'set bios bootmode uefi successful' } elif response_pending_url.status == 405: result = {'ret': False, 'msg': "Resource not supported"} else: error_message = utils.get_extended_error( response_pending_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (pending_url, response_pending_url.status, error_message) } # 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 reset_bios_default(ip, login_account, login_password, system_id): """Reset the BIOS attributes to default :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 reset bios default 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"} return result try: # 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"} 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 ComputerBios resource bios_url = response_system_url.dict['Bios']['@odata.id'] else: error_message = utils.get_extended_error(response_system_url) result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message)} return result response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: # Get the Bios reset url reset_bios_url = response_bios_url.dict['Actions']['#Bios.ResetBios']['target'] # Reset bios default headers = {"Content-Type":"application/json"} if "settings" in reset_bios_url: body = {"ResetType": "default"} response_reset_bios = REDFISH_OBJ.post(reset_bios_url, body=body, headers=headers) else: response_reset_bios = REDFISH_OBJ.post(reset_bios_url, headers=headers) if response_reset_bios.status in [200, 204]: result = {'ret': True, 'msg': 'Reset bios default successfully'} else: error_message = utils.get_extended_error(response_reset_bios) result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s"% (reset_bios_url, response_reset_bios.status, error_message)} return result else: error_message = utils.get_extended_error(response_bios_url) result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message)} return result except Except as e: result = {'ret': False, 'msg': "error_message: %s" % (e)} finally: # Logout of the current session REDFISH_OBJ.logout() return result
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
def set_bios_password(ip, login_account, login_password, system_id, bios_password_name, bios_password): """Set Bios password :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 bios_password_name: Bios password name by user specified :type bios_password_name: string :params bios_password: Bios password by user specified :type bios_password: string :returns: returns set bios password 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" } return result try: # 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" } 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 ComputerBios resource bios_url = response_system_url.dict['Bios']['@odata.id'] else: error_message = utils.get_extended_error(response_system_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message) } return result response_bios_url = REDFISH_OBJ.get(bios_url, None) if response_bios_url.status == 200: # Get the change password url change_password_url = response_bios_url.dict['Actions'][ '#Bios.ChangePassword']['target'] # Set Password info PasswordName = bios_password_name new_password = bios_password parameter = { "PasswordName": PasswordName, "NewPassword": new_password } # Change password response_change_password = REDFISH_OBJ.post( change_password_url, body=parameter) if response_change_password.status in [200, 204]: result = { 'ret': True, 'msg': 'Setting BIOS password successfully' } else: error_message = utils.get_extended_error( response_change_password) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (change_password_url, response_change_password.status, error_message) } return result else: error_message = utils.get_extended_error(response_bios_url) result = { 'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message) } return result except Exception as e: result = {'ret': False, 'msg': "error_message: %s" % (e)} finally: # Logout of the current session REDFISH_OBJ.logout() return result