├── LICENSE ├── README.md ├── ansible-playbooks ├── README.md ├── command_get_server_asset_tag.yml ├── command_set_server_asset_tag.yml ├── create_output_file.yml ├── disable_pxe.yml ├── eject_virtual_media.yml ├── enable_pxe.yml ├── get_bios_attributes.yml ├── get_boot_override.yml ├── get_cpu_inventory.yml ├── get_disk_inventory.yml ├── get_fan_inventory.yml ├── get_firmware_inventory.yml ├── get_memory_inventory.yml ├── get_nic_inventory.yml ├── get_psu_inventory.yml ├── get_storage_controller_inventory.yml ├── get_system_inventory.yml ├── get_system_model.yml ├── get_virtual_media.yml ├── insert_virtual_media.yml ├── lenovoxcc_eject_all_virtual_media.yml ├── lenovoxcc_eject_virtual_media.yml ├── lenovoxcc_insert_virtual_media.yml ├── power_force_off.yml ├── power_force_restart.yml ├── power_graceful_restart.yml ├── power_graceful_shutdown.yml ├── power_on.yml ├── restart_manager.yml ├── set_bios_attributes.yml ├── set_bootmode_legacy.yml ├── set_bootmode_uefi.yml ├── set_onetime_boot.yml ├── update_BMC_firmware.yml ├── update_UEFI_firmware.yml └── update_bmc_user_password.yml ├── examples ├── add_event_subscriptions.py ├── clear_sessions.py ├── clear_system_log.py ├── config.ini ├── del_event_subscriptions.py ├── del_tasks.py ├── disable_bmc_user.py ├── disable_secure_boot.py ├── enable_bmc_user.py ├── enable_secure_boot.py ├── firmware_startupdate.py ├── get_all_bios_attributes.py ├── get_all_tasks.py ├── get_bios_attribute.py ├── get_bios_attribute_metadata.py ├── get_bios_bootmode.py ├── get_bmc_inventory.py ├── get_bmc_ntp.py ├── get_chassis_indicator_led.py ├── get_chassis_inventory.py ├── get_cpu_inventory.py ├── get_event_subscriptions.py ├── get_fan_inventory.py ├── get_fw_inventory.py ├── get_hostinterface.py ├── get_memory_inventory.py ├── get_metric_definition_report.py ├── get_networkprotocol_info.py ├── get_nic_inventory.py ├── get_pci_inventory.py ├── get_power_limit.py ├── get_power_metrics.py ├── get_power_redundancy.py ├── get_power_state.py ├── get_psu_inventory.py ├── get_schema.py ├── get_secure_boot_status.py ├── get_serial_interfaces.py ├── get_server_boot_once.py ├── get_server_boot_once_types.py ├── get_sessions.py ├── get_storage_inventory.py ├── get_system_inventory.py ├── get_system_log.py ├── get_system_reset_types.py ├── get_temperatures_inventory.py ├── get_virtual_media.py ├── get_volt_inventory.py ├── lenovo_add_alert_recipient.py ├── lenovo_bmc_config_backup.py ├── lenovo_bmc_config_restore.py ├── lenovo_bmc_license_delete.py ├── lenovo_bmc_license_export.py ├── lenovo_bmc_license_getinfo.py ├── lenovo_bmc_license_import.py ├── lenovo_callhome_getinfo.py ├── lenovo_callhome_setting.py ├── lenovo_create_bmc_user.py ├── lenovo_create_raid_volume.py ├── lenovo_del_alert_recipient.py ├── lenovo_delete_bmc_user.py ├── lenovo_delete_raid_volume.py ├── lenovo_delete_ssh_pubkey.py ├── lenovo_eklm_certificate_generate_csr.py ├── lenovo_eklm_certificate_import.py ├── lenovo_eklm_keyserver_config.py ├── lenovo_eklm_keyserver_getinfo.py ├── lenovo_ekms_localcache_setting.py ├── lenovo_export_ffdc_data.py ├── lenovo_generate_snmp_engineid.py ├── lenovo_get_alert_recipients.py ├── lenovo_get_bios_boot_order.py ├── lenovo_get_bios_boot_order_network.py ├── lenovo_get_bmc_external_ldap.py ├── lenovo_get_bmc_user_accounts.py ├── lenovo_get_bmc_user_global.py ├── lenovo_get_bmc_user_ldap_policy.py ├── lenovo_get_cpu_inventory.py ├── lenovo_get_snmp_global.py ├── lenovo_get_ssh_pubkey.py ├── lenovo_httpfs_certificate_delete.py ├── lenovo_httpfs_certificate_disable.py ├── lenovo_httpfs_certificate_enable.py ├── lenovo_httpfs_certificate_getinfo.py ├── lenovo_httpfs_certificate_import.py ├── lenovo_import_ssh_pubkey.py ├── lenovo_ldap_certificate_add.py ├── lenovo_ldap_certificate_disable.py ├── lenovo_ldap_certificate_enable.py ├── lenovo_mount_virtual_media.py ├── lenovo_set_amt.py ├── lenovo_set_bios_boot_order.py ├── lenovo_set_bios_boot_order_network.py ├── lenovo_set_bmc_config_default.py ├── lenovo_set_bmc_dns.py ├── lenovo_set_bmc_external_ldap.py ├── lenovo_set_bmc_user_global.py ├── lenovo_set_bmc_user_ldap_policy.py ├── lenovo_set_serial_interfaces.py ├── lenovo_set_snmp_global.py ├── lenovo_ssl_certificate_generate_csr.py ├── lenovo_ssl_certificate_getinfo.py ├── lenovo_ssl_certificate_import.py ├── lenovo_umount_virtual_media.py ├── lenovo_update_firmware.py ├── lenovo_update_raid_volume.py ├── lenovo_utils.py ├── manage_inventory.py ├── mount_virtual_media.py ├── raw_command_get.py ├── raw_command_patch.py ├── raw_command_post.py ├── reset_bios_default.py ├── reset_secure_boot.py ├── restart_bmc.py ├── send_test_event.py ├── send_test_metric.py ├── set_bios_attribute.py ├── set_bios_bootmode_legacy.py ├── set_bios_bootmode_uefi.py ├── set_bios_password.py ├── set_bmc_hostname.py ├── set_bmc_ipv4.py ├── set_bmc_ntp.py ├── set_bmc_timezone.py ├── set_bmc_vlanid.py ├── set_chassis_indicator_led.py ├── set_networkprotocol.py ├── set_power_limit.py ├── set_power_state.py ├── set_raid_encryption_mode.py ├── set_serial_interfaces.py ├── set_server_asset_tag.py ├── set_server_boot_once.py ├── set_system_name.py ├── umount_virtual_media.py ├── update_bmc_user_account_type.py ├── update_bmc_user_password.py ├── update_bmc_user_snmpinfo.py └── update_firmware.py └── products_supported.txt /README.md: -------------------------------------------------------------------------------- 1 | # python-redfish-lenovo 2 | 3 | Sample Python scripts for using the Redfish API on Lenovo servers 4 | 5 | Description 6 | ---------- 7 | 8 | This project includes a set of sample Python scripts that utilize the Redfish API to manage Lenovo ThinkSystem servers. The scripts use the DMTF python-redfish-library 9 | 10 | For more information on the Redfish API, visit 11 | 12 | Installing 13 | ---------- 14 | 15 | * To install the python-redfish-library 16 | 17 | `pip install redfish` 18 | 19 | * To install configparser: 20 | 21 | `pip install configparser` 22 | 23 | As configparser only support python3 from 5.0.0, if you are using python2.7, please specify version 4.0.2 while installing 24 | 25 | `pip install configparser==4.0.2` 26 | 27 | * To install requests: 28 | 29 | `pip install requests` 30 | 31 | Requirements 32 | ---------- 33 | 34 | * python-redfish-library need to be installed 35 | 36 | Usage 37 | ---------- 38 | A set of python examples is provided under the examples directory of this project. 39 | 40 | * Common parameters configuration 41 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 42 | You can use a configuration file to store common parameters for the Lenovo Python Redfish Scripts, 43 | such as the BMC IP address, user name, and password. Default configuration file is config.ini. 44 | You can create your own configuration file and specify it using the "--config" option. 45 | The scripts will load config.ini automatically if no configuration file is specified in command line. 46 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 47 | * Using the python examples to get and set values 48 | 49 | Simply run the python script to print out the values from the HTTP GET operation. 50 | 51 | This example prints the current system power state (such as On or Off) 52 | 53 | cd examples 54 | python get_power_state.py 55 | This example prints the system reset types that are supported by this server, then passes one of the values (ForceOff) to force the server to shutdown: 56 | 57 | cd examples 58 | python lenovo_get_reset_types.py 59 | ['On', 'Nmi', 'GracefulShutdown', 'GracefulRestart', 'ForceOn', 'ForceOff', 'ForceRestart'] 60 | 61 | Python lenovo_set_reset_types.py ForceOff 62 | 63 | Note: There are three scripts (raw_command_*.py) to support raw redfish get/patch/post requests. If existing scripts can't meet your requirement, please try them. 64 | 65 | Contributing 66 | ---------- 67 | 68 | 1. Fork it! 69 | 2. Create your feature branch: `git checkout -b my-new-feature` 70 | 3. Commit your changes: `git commit -am 'Add some feature'` 71 | 4. Push to the branch: `git push origin my-new-feature` 72 | 5. Submit a pull request :D 73 | 74 | Copyright and License 75 | --------------------- 76 | 77 | Copyright 2019 Lenovo Corporation 78 | 79 | Licensed under the Apache License, Version 2.0 (the "License"); you may 80 | not use this file except in compliance with the License. You may obtain 81 | a copy of the License at 82 | 83 | http://www.apache.org/licenses/LICENSE-2.0 84 | 85 | Unless required by applicable law or agreed to in writing, software 86 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 87 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 88 | License for the specific language governing permissions and limitations 89 | under the License. 90 | -------------------------------------------------------------------------------- /ansible-playbooks/README.md: -------------------------------------------------------------------------------- 1 | # ansible-playbooks 2 | 3 | Sample Ansible playbooks for using the Redfish API on Lenovo servers 4 | 5 | Description 6 | ---------- 7 | 8 | This folder includes a set of sample Ansible playbooks that utilize the Redfish API to manage Lenovo ThinkSystem servers. The playbooks use redfish_facts/redfish_command/redfish_config modules which are in Ansible or community.general collection since Ansible version 2.10 9 | 10 | For more information on the Redfish API, visit 11 | 12 | For more information on the Ansible, visit 13 | 14 | For more information on the community.general collection, visit 15 | 16 | Installing 17 | ---------- 18 | 19 | * To install Ansible: 20 | 21 | `pip install ansible` 22 | 23 | Without version specified, newest version will be installed. If you want specific version, specify it as below: 24 | 25 | `pip install ansible==2.8` 26 | 27 | * To install community.general collection (Needed since Ansible version 2.10): 28 | 29 | `ansible-galaxy collection install community.general` 30 | 31 | Requirements 32 | ---------- 33 | 34 | * Ansible and community.general collection need to be installed 35 | 36 | Usage 37 | ---------- 38 | A set of playbook examples is provided under the ansible-playbooks directory of this project. 39 | 40 | * Common variables 41 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 42 | Variable "baseuri" represent BMC IP address, and variable "username" and "password" are used for BMC authentification. They should be configured in your inventory file before starting use playbooks. The results of get action playbooks which start with "get_" would be saved to files which's format is defined in create_output_file.yml. Please set variable "rootdir" to a local directory where you want to place results. 43 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 44 | 45 | * Using the ansible playbook to get bios attributes 46 | 47 | This example save the bios attributes of your myhosts to files (Default location is "output" named folder in current directory) 48 | 49 | cd ansible-playbooks 50 | ansible-playbook get_bios_attributes.yml 51 | 52 | * Using the ansible playbook to restart server 53 | 54 | This example reaceful restart servers defined in myhosts inventory file 55 | 56 | cd ansible-playbooks 57 | ansible-playbook power_graceful_restart.yml 58 | 59 | Contributing 60 | ---------- 61 | 62 | 1. Fork it! 63 | 2. Create your feature branch: `git checkout -b my-new-feature` 64 | 3. Commit your changes: `git commit -am 'Add some feature'` 65 | 4. Push to the branch: `git push origin my-new-feature` 66 | 5. Submit a pull request :D 67 | 68 | Copyright and License 69 | --------------------- 70 | 71 | Copyright 2021 Lenovo Corporation 72 | 73 | Licensed under the Apache License, Version 2.0 (the "License"); you may 74 | not use this file except in compliance with the License. You may obtain 75 | a copy of the License at 76 | 77 | http://www.apache.org/licenses/LICENSE-2.0 78 | 79 | Unless required by applicable law or agreed to in writing, software 80 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 81 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 82 | License for the specific language governing permissions and limitations 83 | under the License. 84 | -------------------------------------------------------------------------------- /ansible-playbooks/command_get_server_asset_tag.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get server asset tag 5 | gather_facts: False 6 | 7 | tasks: 8 | - name: Set baseuri to inventory_hostname when it is not defined 9 | set_fact: 10 | baseuri: "{{ inventory_hostname }}" 11 | when: baseuri is undefined 12 | 13 | - name: Fail when username or password is undefined 14 | debug: 15 | msg: "Variables username and password must be defined for BMC connection" 16 | failed_when: True 17 | when: username is undefined or password is undefined 18 | 19 | - name: Get system inventory 20 | command: python ../examples/get_system_inventory.py -i "{{ baseuri }}" -u "{{ username }}" -p "{{ password }}" 21 | changed_when: False 22 | register: result 23 | - set_fact: 24 | system_inventory: "{{ result.stdout }}" 25 | 26 | - name: Get AssetTag from system inventory 27 | set_fact: 28 | assettag: "{{ system_inventory[0].AssetTag }}" 29 | - debug: 30 | msg: "AssetTag = {{ assettag }}" 31 | -------------------------------------------------------------------------------- /ansible-playbooks/command_set_server_asset_tag.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Set server asset tag 5 | gather_facts: False 6 | 7 | vars: 8 | assettag: "asset_tag_value" 9 | 10 | tasks: 11 | - name: Set baseuri to inventory_hostname when it is not defined 12 | set_fact: 13 | baseuri: "{{ inventory_hostname }}" 14 | when: baseuri is undefined 15 | 16 | - name: Fail when username or password is undefined 17 | debug: 18 | msg: "Variables username and password must be defined for BMC connection" 19 | failed_when: True 20 | when: username is undefined or password is undefined 21 | 22 | - name: Set server asset tag 23 | command: python ../examples/set_server_asset_tag.py -i "{{ baseuri }}" -u "{{ username }}" -p "{{ password }}" --assettag "{{ assettag }}" 24 | register: result 25 | - debug: 26 | msg: "{{ result.stdout }}" 27 | -------------------------------------------------------------------------------- /ansible-playbooks/create_output_file.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Define timestamp 3 | set_fact: timestamp="{{ lookup('pipe', 'date +%Y%m%d_%H%M%S') }}" 4 | run_once: true 5 | 6 | - name: Set Default rootdir 7 | set_fact: rootdir="./output" 8 | when: rootdir is undefined 9 | run_once: true 10 | 11 | - name: Set Default host 12 | set_fact: host={{baseuri}} 13 | when: host is undefined 14 | 15 | - name: Define file to place results 16 | set_fact: template={{rootdir}}/{{host}}/{{host}}_{{datatype}}_{{timestamp}} 17 | 18 | - name: Create dropoff directory for host 19 | file: 20 | path: "{{ rootdir }}/{{ host }}" 21 | state: directory 22 | -------------------------------------------------------------------------------- /ansible-playbooks/disable_pxe.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Disable PXE in NICs 5 | gather_facts: False 6 | 7 | vars: 8 | - attribute_name: NetworkStackSettings_IPv4PXESupport 9 | - attribute_value: Disable 10 | 11 | tasks: 12 | 13 | - name: Get system model 14 | include_tasks: get_system_model.yml 15 | 16 | - name: update attribute_name and attribute_value for SR635/SR655 17 | set_fact: 18 | attribute_name: Q00181_Ipv4_PXE_Support 19 | attribute_value: Disabled 20 | when: system_model == "ThinkSystem SR635" or system_model == "ThinkSystem SR655" 21 | 22 | - name: Set {{ attribute_name }} to {{ attribute_value }} 23 | redfish_config: 24 | category: Systems 25 | command: SetBiosAttributes 26 | bios_attribute_name: "{{ attribute_name }}" 27 | bios_attribute_value: "{{ attribute_value }}" 28 | baseuri: "{{ baseuri }}" 29 | username: "{{ username }}" 30 | password: "{{ password }}" 31 | timeout: 20 32 | register: bios_attribute 33 | 34 | - name: Reboot system to apply new BIOS settings 35 | redfish_command: 36 | category: Systems 37 | command: PowerReboot 38 | baseuri: "{{ baseuri }}" 39 | username: "{{ username }}" 40 | password: "{{ password }}" 41 | timeout: 20 42 | when: bios_attribute.changed 43 | -------------------------------------------------------------------------------- /ansible-playbooks/eject_virtual_media.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Eject Virtual Media 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Eject Virtual Media from Manager 10 | community.general.redfish_command: 11 | category: Manager 12 | command: VirtualMediaEject 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | virtual_media: 17 | #HTTP protocol 18 | # image_url: "http://10.245.52.18/upload/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 19 | 20 | #NFS protocol 21 | image_url: "10.245.52.18:/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for XCC 22 | # image_url: "//10.245.52.18/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for SR635/SR645 23 | transfer_protocol_type: NFS 24 | 25 | #CIFS protocol 26 | # image_url: "//10.245.52.18/cifs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 27 | # transfer_protocol_type: CIFS 28 | # username: redfish 29 | # password: "123456" 30 | resource_id: "{{ resource_id }}" 31 | register: result 32 | ignore_errors: yes 33 | 34 | - block: 35 | - name: Eject Virtual Media from Systems 36 | redfish_command: 37 | category: Systems 38 | command: VirtualMediaEject 39 | baseuri: "{{ baseuri }}" 40 | username: "{{ username }}" 41 | password: "{{ password }}" 42 | timeout: 20 43 | virtual_media: 44 | image_url: "10.245.52.18:/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for XCC 45 | transfer_protocol_type: NFS 46 | resource_id: "{{ resource_id }}" 47 | when: result is failure 48 | -------------------------------------------------------------------------------- /ansible-playbooks/enable_pxe.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Enable PXE in NICs 5 | gather_facts: False 6 | 7 | vars: 8 | - attribute_name: NetworkStackSettings_IPv4PXESupport 9 | - attribute_value: Enable 10 | 11 | tasks: 12 | 13 | - name: Get system model 14 | include_tasks: get_system_model.yml 15 | 16 | - name: update attribute_name and attribute_value for SR635/SR655 17 | set_fact: 18 | attribute_name: Q00181_Ipv4_PXE_Support 19 | attribute_value: Enabled 20 | when: system_model == "ThinkSystem SR635" or system_model == "ThinkSystem SR655" 21 | 22 | - name: Set {{ attribute_name }} to {{ attribute_value }} 23 | redfish_config: 24 | category: Systems 25 | command: SetBiosAttributes 26 | bios_attribute_name: "{{ attribute_name }}" 27 | bios_attribute_value: "{{ attribute_value }}" 28 | baseuri: "{{ baseuri }}" 29 | username: "{{ username }}" 30 | password: "{{ password }}" 31 | timeout: 20 32 | register: bios_attribute 33 | 34 | - name: Reboot system to apply new BIOS settings 35 | redfish_command: 36 | category: Systems 37 | command: PowerReboot 38 | baseuri: "{{ baseuri }}" 39 | username: "{{ username }}" 40 | password: "{{ password }}" 41 | timeout: 20 42 | when: bios_attribute.changed 43 | -------------------------------------------------------------------------------- /ansible-playbooks/get_bios_attributes.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get BIOS attributes 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: BiosAttributes 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get BIOS attributes 16 | redfish_info: 17 | category: Systems 18 | command: GetBiosAttributes 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_boot_override.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get Boot Override 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: BootOverride 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get Boot Override information 16 | redfish_info: 17 | category: Systems 18 | command: GetBootOverride 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_cpu_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get cpu inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: CpuInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get cpu inventory 16 | redfish_info: 17 | category: Systems 18 | command: GetCpuInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_disk_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get disk inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: DiskInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get disk inventory 16 | redfish_info: 17 | category: Systems 18 | command: GetDiskInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_fan_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get fan inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: FanInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get fan inventory 16 | redfish_info: 17 | category: Chassis 18 | command: GetFanInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_firmware_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get firmware inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: FirmwareInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get firmware inventory 16 | redfish_info: 17 | category: Update 18 | command: GetFirmwareInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Set var firmware_entries 26 | set_fact: 27 | firmware_entries: "{{ result.redfish_facts.firmware.entries }}" 28 | 29 | - name: Get BMC firmware version 30 | set_fact: 31 | BMCFWVersion: "{{ [item.SoftwareId, item.Version] | join }}" 32 | when: item.Id == 'BMC-Primary' 33 | loop: 34 | "{{ firmware_entries }}" 35 | 36 | - debug: var=BMCFWVersion 37 | 38 | - name: Get UEFI firmware version 39 | set_fact: 40 | UEFIFWVersion: "{{ [item.SoftwareId, item.Version] | join }}" 41 | when: item.Id == 'UEFI' 42 | loop: 43 | "{{ firmware_entries }}" 44 | 45 | - debug: var=UEFIFWVersion 46 | 47 | - name: Copy results to output file 48 | copy: 49 | content: "{{ result | to_nice_json }}" 50 | dest: "{{ template }}.json" 51 | -------------------------------------------------------------------------------- /ansible-playbooks/get_memory_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get memory inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: MemoryInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get memory inventory 16 | redfish_info: 17 | category: Systems 18 | command: GetMemoryInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_nic_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get nic inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: NicInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get nic inventory 16 | redfish_info: 17 | category: Systems 18 | command: GetNicInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_psu_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get psu inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: PsuInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get psu inventory 16 | redfish_info: 17 | category: Chassis 18 | command: GetPsuInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_storage_controller_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get storage controller inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: StorageControllerInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get storage controller inventory 16 | redfish_info: 17 | category: Systems 18 | command: GetStorageControllerInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_system_inventory.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get system inventory 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: SystemInventory 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get system inventory 16 | redfish_info: 17 | category: Systems 18 | command: GetSystemInventory 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | timeout: 20 23 | register: result 24 | 25 | - name: Copy results to output file 26 | copy: 27 | content: "{{ result | to_nice_json }}" 28 | dest: "{{ template }}.json" 29 | -------------------------------------------------------------------------------- /ansible-playbooks/get_system_model.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Set default system_model 3 | set_fact: system_model="" 4 | when: system_model is undefined 5 | 6 | - name: Getting system inventory 7 | redfish_info: 8 | category: Systems 9 | command: GetSystemInventory 10 | baseuri: "{{ baseuri }}" 11 | username: "{{ username }}" 12 | password: "{{ password }}" 13 | timeout: 20 14 | register: result 15 | 16 | - name: Get Model from system inventory 17 | set_fact: 18 | system_model: "{{ result.redfish_facts.system.entries[0][1].Model }}" 19 | -------------------------------------------------------------------------------- /ansible-playbooks/get_virtual_media.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Get Virtual Media information 5 | gather_facts: False 6 | 7 | vars: 8 | datatype: VirtualMedia 9 | 10 | tasks: 11 | 12 | - name: Define output file 13 | include_tasks: create_output_file.yml 14 | 15 | - name: Get Virtual Media information from Manager 16 | redfish_info: 17 | category: Manager 18 | command: GetVirtualMedia 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | register: result 23 | 24 | - name: Copy results to output file 25 | copy: 26 | content: "{{ result.redfish_facts.virtual_media.entries | to_nice_json }}" 27 | dest: "{{ template }}.json" 28 | when: result.redfish_facts.virtual_media.ret 29 | 30 | - name: Set var virtualMedia 31 | set_fact: 32 | virtualMedia: "{{ result.redfish_facts.virtual_media.entries[0][1] }}" 33 | when: result.redfish_facts.virtual_media.ret 34 | 35 | - block: 36 | - name: Get Virtual Media information from Systems 37 | redfish_info: 38 | category: Systems 39 | command: GetVirtualMedia 40 | baseuri: "{{ baseuri }}" 41 | username: "{{ username }}" 42 | password: "{{ password }}" 43 | register: result2 44 | 45 | - name: Copy results to output file 46 | copy: 47 | content: "{{ result2.redfish_facts.virtual_media.entries | to_nice_json }}" 48 | dest: "{{ template }}.json" 49 | 50 | - name: Set var virtualMedia 51 | set_fact: 52 | virtualMedia: "{{ result2.redfish_facts.virtual_media.entries[0][1] }}" 53 | when: not result.redfish_facts.virtual_media.ret 54 | 55 | -------------------------------------------------------------------------------- /ansible-playbooks/insert_virtual_media.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Insert Virtual Media 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Insert Virtual Media from Manager 10 | redfish_command: 11 | category: Manager 12 | command: VirtualMediaInsert 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | virtual_media: 18 | #HTTP protocol 19 | # image_url: "http://10.245.52.18/upload/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 20 | 21 | #NFS protocol 22 | image_url: "10.245.52.18:/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for XCC 23 | # image_url: "//10.245.52.18/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for SR635/SR645 24 | transfer_protocol_type: NFS 25 | 26 | #CIFS protocol 27 | # image_url: "//10.245.52.18/cifs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 28 | # transfer_protocol_type: CIFS 29 | # username: redfish 30 | # password: "123456" 31 | media_types: 32 | - CD 33 | resource_id: "{{ resource_id }}" 34 | register: result 35 | ignore_errors: yes 36 | 37 | - block: 38 | - name: Insert Virtual Media from Systems 39 | redfish_command: 40 | category: Systems 41 | command: VirtualMediaInsert 42 | baseuri: "{{ baseuri }}" 43 | username: "{{ username }}" 44 | password: "{{ password }}" 45 | timeout: 20 46 | virtual_media: 47 | image_url: "10.245.52.18:/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for XCC 48 | transfer_protocol_type: NFS 49 | media_types: 50 | - CD 51 | resource_id: "{{ resource_id }}" 52 | when: result is failure 53 | 54 | -------------------------------------------------------------------------------- /ansible-playbooks/lenovoxcc_eject_all_virtual_media.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Eject all Virtual Media 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Eject all Virtual Media 10 | community.general.xcc_redfish_command: 11 | category: Manager 12 | command: VirtualMediaEject 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | resource_id: "{{ resource_id }}" 17 | -------------------------------------------------------------------------------- /ansible-playbooks/lenovoxcc_eject_virtual_media.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Eject Virtual Media 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Eject Virtual Media 10 | community.general.xcc_redfish_command: 11 | category: Manager 12 | command: VirtualMediaEject 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | virtual_media: 17 | #HTTP protocol 18 | # image_url: "http://10.245.52.18/upload/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 19 | 20 | #NFS protocol 21 | image_url: "10.245.52.18:/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for XCC 22 | # image_url: "//10.245.52.18/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for SR635/SR645 23 | transfer_protocol_type: NFS 24 | 25 | #CIFS protocol 26 | # image_url: "//10.245.52.18/cifs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 27 | # transfer_protocol_type: CIFS 28 | # username: redfish 29 | # password: "123456" 30 | resource_id: "{{ resource_id }}" 31 | -------------------------------------------------------------------------------- /ansible-playbooks/lenovoxcc_insert_virtual_media.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Insert Virtual Media 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Insert Virtual Media 10 | community.general.xcc_redfish_command: 11 | category: Manager 12 | command: VirtualMediaInsert 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | virtual_media: 17 | #HTTP protocol 18 | # image_url: "http://10.245.52.18/upload/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 19 | 20 | #NFS protocol 21 | image_url: "10.245.52.18:/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for XCC 22 | # image_url: "//10.245.52.18/home/nfs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" #for SR635/SR645 23 | transfer_protocol_type: NFS 24 | 25 | #CIFS protocol 26 | # image_url: "//10.245.52.18/cifs/minimal_linux_live_28-Jan-2018_64-bit_bios.iso" 27 | # transfer_protocol_type: CIFS 28 | # username: redfish 29 | # password: "123456" 30 | media_types: 31 | - CD 32 | resource_id: "{{ resource_id }}" 33 | -------------------------------------------------------------------------------- /ansible-playbooks/power_force_off.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Manage System Power - Force Off 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Turn system power off 10 | redfish_command: 11 | category: Systems 12 | command: PowerForceOff 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | register: power 18 | -------------------------------------------------------------------------------- /ansible-playbooks/power_force_restart.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Manage System Power - Force restart 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Restart system power forcefully 10 | redfish_command: 11 | category: Systems 12 | command: PowerForceRestart 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | register: power 18 | -------------------------------------------------------------------------------- /ansible-playbooks/power_graceful_restart.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Manage System Power - Greaceful restart 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Restart system power gracefully 10 | redfish_command: 11 | category: Systems 12 | command: PowerReboot 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | register: power 18 | -------------------------------------------------------------------------------- /ansible-playbooks/power_graceful_shutdown.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Manage System Power - Graceful shutdown 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Shutdown system power gracefully 10 | redfish_command: 11 | category: Systems 12 | command: PowerGracefulShutdown 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | register: power 18 | -------------------------------------------------------------------------------- /ansible-playbooks/power_on.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Manage System Power - Turn on 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Turn system power on 10 | redfish_command: 11 | category: Systems 12 | command: PowerOn 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | register: power 18 | -------------------------------------------------------------------------------- /ansible-playbooks/restart_manager.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Restart Manager 5 | gather_facts: False 6 | 7 | tasks: 8 | 9 | - name: Restart Manager gracefully 10 | redfish_command: 11 | category: Manager 12 | command: GracefulRestart 13 | baseuri: "{{ baseuri }}" 14 | username: "{{ username }}" 15 | password: "{{ password }}" 16 | timeout: 20 17 | register: result 18 | -------------------------------------------------------------------------------- /ansible-playbooks/set_bios_attributes.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Set bios attribute and reboot 5 | gather_facts: False 6 | 7 | vars: 8 | - attribute_name: AdvancedRAS_MachineCheckRecovery 9 | - attribute_value: Disabled 10 | 11 | tasks: 12 | 13 | - shell: 'ansible --version' 14 | register: ansible_version 15 | 16 | - block: 17 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version less than 2.10.0 18 | redfish_config: 19 | category: Systems 20 | command: SetBiosAttributes 21 | bios_attribute_name: "{{ attribute_name }}" 22 | bios_attribute_value: "{{ attribute_value }}" 23 | baseuri: "{{ baseuri }}" 24 | username: "{{ username }}" 25 | password: "{{ password }}" 26 | timeout: 20 27 | register: bios_attribute_less 28 | when: ansible_version['full'] is version('2.10.0', '<') 29 | 30 | - block: 31 | - name: Set multiple bios attributes for ansible version greater than 2.10.0 32 | redfish_config: 33 | category: Systems 34 | command: SetBiosAttributes 35 | bios_attributes: 36 | AdvancedRAS_MachineCheckRecovery: "Disabled" 37 | Processors_UPIPrefetcher: "Disabled" 38 | baseuri: "{{ baseuri }}" 39 | username: "{{ username }}" 40 | password: "{{ password }}" 41 | timeout: 20 42 | register: bios_attribute_greater 43 | when: ansible_version['full'] is version('2.10.0', '>') 44 | 45 | - name: Reboot system to apply new BIOS settings 46 | redfish_command: 47 | category: Systems 48 | command: PowerForceRestart 49 | baseuri: "{{ baseuri }}" 50 | username: "{{ username }}" 51 | password: "{{ password }}" 52 | timeout: 20 53 | register: power 54 | when: bios_attribute_less.changed or bios_attribute_greater.changed 55 | ignore_errors: yes 56 | -------------------------------------------------------------------------------- /ansible-playbooks/set_bootmode_legacy.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Set boot mode to legacy and reboot 5 | gather_facts: False 6 | 7 | vars: 8 | - attribute_name: BootModes_SystemBootMode 9 | - attribute_value: LegacyMode 10 | 11 | tasks: 12 | 13 | - shell: 'ansible --version' 14 | register: ansible_version 15 | 16 | - name: Get system model 17 | include_tasks: get_system_model.yml 18 | 19 | - name: update attribute_name and attribute_value for SR635/SR655 20 | set_fact: 21 | attribute_name: Q00001_Boot_Mode 22 | attribute_value: Legacy_only 23 | when: system_model == "ThinkSystem SR635" or system_model == "ThinkSystem SR655" 24 | 25 | - block: 26 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version less than 2.10.0 27 | redfish_config: 28 | category: Systems 29 | command: SetBiosAttributes 30 | bios_attribute_name: "{{ attribute_name }}" 31 | bios_attribute_value: "{{ attribute_value }}" 32 | baseuri: "{{ baseuri }}" 33 | username: "{{ username }}" 34 | password: "{{ password }}" 35 | timeout: 20 36 | register: bios_attribute_less 37 | when: ansible_version['full'] is version('2.10.0', '<') 38 | 39 | - block: 40 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version greater than 2.10.0 and not AMD1P 41 | redfish_config: 42 | category: Systems 43 | command: SetBiosAttributes 44 | bios_attributes: 45 | BootModes_SystemBootMode: "{{ attribute_value }}" 46 | baseuri: "{{ baseuri }}" 47 | username: "{{ username }}" 48 | password: "{{ password }}" 49 | timeout: 20 50 | register: bios_attribute_XCC 51 | when: ansible_version['full'] is version('2.10.0', '>') and system_model != "ThinkSystem SR635" and system_model != "ThinkSystem SR655" 52 | 53 | - block: 54 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version greater than 2.10.0 and AMD1P 55 | redfish_config: 56 | category: Systems 57 | command: SetBiosAttributes 58 | bios_attributes: 59 | Q00001_Boot_Mode: "{{ attribute_value }}" 60 | baseuri: "{{ baseuri }}" 61 | username: "{{ username }}" 62 | password: "{{ password }}" 63 | timeout: 20 64 | register: bios_attribute_AMD 65 | when: ansible_version['full'] is version('2.10.0', '>') and (system_model == "ThinkSystem SR635" or system_model == "ThinkSystem SR655") 66 | 67 | - name: Reboot system to apply new BIOS settings 68 | redfish_command: 69 | category: Systems 70 | command: PowerForceRestart 71 | baseuri: "{{ baseuri }}" 72 | username: "{{ username }}" 73 | password: "{{ password }}" 74 | timeout: 20 75 | register: power 76 | when: bios_attribute_less.changed or bios_attribute_XCC.changed or bios_attribute_AMD.changed 77 | ignore_errors: yes 78 | -------------------------------------------------------------------------------- /ansible-playbooks/set_bootmode_uefi.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Set boot mode to UEFI and reboot 5 | gather_facts: False 6 | 7 | vars: 8 | - attribute_name: BootModes_SystemBootMode 9 | - attribute_value: UEFIMode 10 | 11 | tasks: 12 | 13 | - shell: 'ansible --version' 14 | register: ansible_version 15 | 16 | - name: Get system model 17 | include_tasks: get_system_model.yml 18 | 19 | - name: update attribute_name and attribute_value for SR635/SR655 20 | set_fact: 21 | attribute_name: Q00001_Boot_Mode 22 | attribute_value: UEFI_only 23 | when: system_model == "ThinkSystem SR635" or system_model == "ThinkSystem SR655" 24 | 25 | - block: 26 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version less than 2.10.0 27 | redfish_config: 28 | category: Systems 29 | command: SetBiosAttributes 30 | bios_attribute_name: "{{ attribute_name }}" 31 | bios_attribute_value: "{{ attribute_value }}" 32 | baseuri: "{{ baseuri }}" 33 | username: "{{ username }}" 34 | password: "{{ password }}" 35 | timeout: 20 36 | register: bios_attribute_less 37 | when: ansible_version['full'] is version('2.10.0', '<') 38 | 39 | - block: 40 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version greater than 2.10.0 and not AMD1P 41 | redfish_config: 42 | category: Systems 43 | command: SetBiosAttributes 44 | bios_attributes: 45 | BootModes_SystemBootMode: "{{ attribute_value }}" 46 | baseuri: "{{ baseuri }}" 47 | username: "{{ username }}" 48 | password: "{{ password }}" 49 | timeout: 20 50 | register: bios_attribute_XCC 51 | when: ansible_version['full'] is version('2.10.0', '>') and system_model != "ThinkSystem SR635" and system_model != "ThinkSystem SR655" 52 | 53 | - block: 54 | - name: Set {{ attribute_name }} to {{ attribute_value }} for ansible version greater than 2.10.0 and AMD1P 55 | redfish_config: 56 | category: Systems 57 | command: SetBiosAttributes 58 | bios_attributes: 59 | Q00001_Boot_Mode: "{{ attribute_value }}" 60 | baseuri: "{{ baseuri }}" 61 | username: "{{ username }}" 62 | password: "{{ password }}" 63 | timeout: 20 64 | register: bios_attribute_AMD 65 | when: ansible_version['full'] is version('2.10.0', '>') and (system_model == "ThinkSystem SR635" or system_model == "ThinkSystem SR655") 66 | 67 | - name: Reboot system to apply new BIOS settings 68 | redfish_command: 69 | category: Systems 70 | command: PowerForceRestart 71 | baseuri: "{{ baseuri }}" 72 | username: "{{ username }}" 73 | password: "{{ password }}" 74 | timeout: 20 75 | register: power 76 | when: bios_attribute_less.changed or bios_attribute_XCC.changed or bios_attribute_AMD.changed 77 | ignore_errors: yes 78 | -------------------------------------------------------------------------------- /ansible-playbooks/set_onetime_boot.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Set one-time BIOS boot device 5 | gather_facts: False 6 | 7 | vars: 8 | - bootdevice: Cd 9 | 10 | tasks: 11 | 12 | - name: Set one-time boot device to {{ bootdevice }} 13 | redfish_command: 14 | category: Systems 15 | command: SetOneTimeBoot 16 | bootdevice: "{{ bootdevice }}" 17 | baseuri: "{{ baseuri }}" 18 | username: "{{ username }}" 19 | password: "{{ password }}" 20 | timeout: 20 21 | register: bios_onetimeboot 22 | 23 | - name: Reboot system 24 | redfish_command: 25 | category: Systems 26 | command: PowerReboot 27 | baseuri: "{{ baseuri }}" 28 | username: "{{ username }}" 29 | password: "{{ password }}" 30 | timeout: 20 31 | when: bios_onetimeboot.changed 32 | -------------------------------------------------------------------------------- /ansible-playbooks/update_BMC_firmware.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Simple Update BMC 5 | gather_facts: False 6 | 7 | tasks: 8 | - name: Get original tasks 9 | command: python3 ../examples/get_all_tasks.py -i "{{ baseuri }}" -u "{{ username }}" -p "{{ password }}" 10 | register: result_task_org 11 | until: result_task_org.failed == false 12 | retries: 1 13 | delay: 10 14 | 15 | - name: Simple update BMC 16 | redfish_command: 17 | category: Update 18 | command: SimpleUpdate 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | update_image_uri: https://10.245.52.18/upload/update_fw/lnvgy_fw_xcc_cdi3a2q-8.80_anyos_noarch.uxz 23 | register: result 24 | 25 | 26 | - name: Wait with tries until the lastest task state is Completed 27 | command: python3 ../examples/get_all_tasks.py -i "{{ baseuri }}" -u "{{ username }}" -p "{{ password }}" 28 | register: result_task 29 | until: result_task.failed == false and ((result_task.stdout | from_json).Members | difference((result_task_org.stdout | from_json).Members) != []) and ((result_task.stdout | from_json).Members | difference((result_task_org.stdout | from_json).Members) | map(attribute='TaskState') | list | first == "Completed") 30 | retries: 10 31 | delay: 20 32 | 33 | - name: Restart Manager gracefully 34 | redfish_command: 35 | category: Manager 36 | command: GracefulRestart 37 | baseuri: "{{ baseuri }}" 38 | username: "{{ username }}" 39 | password: "{{ password }}" 40 | timeout: 20 41 | register: result 42 | 43 | -------------------------------------------------------------------------------- /ansible-playbooks/update_UEFI_firmware.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: myhosts 3 | connection: local 4 | name: Simple Update UEFI 5 | gather_facts: False 6 | 7 | tasks: 8 | - name: Get original tasks 9 | command: python3 ../examples/get_all_tasks.py -i "{{ baseuri }}" -u "{{ username }}" -p "{{ password }}" 10 | register: result_task_org 11 | until: result_task_org.failed == false 12 | retries: 1 13 | delay: 10 14 | 15 | - name: Simple update UEFI 16 | redfish_command: 17 | category: Update 18 | command: SimpleUpdate 19 | baseuri: "{{ baseuri }}" 20 | username: "{{ username }}" 21 | password: "{{ password }}" 22 | update_image_uri: https://10.245.52.18/upload/update_fw/lnvgy_fw_uefi_ive180g-3.40_anyos_32-64.uxz 23 | register: result 24 | 25 | 26 | - name: Wait with tries until the lastest task state is Completed 27 | command: python3 ../examples/get_all_tasks.py -i "{{ baseuri }}" -u "{{ username }}" -p "{{ password }}" 28 | register: result_task 29 | until: result_task.failed == false and ((result_task.stdout | from_json).Members | difference((result_task_org.stdout | from_json).Members) != []) and ((result_task.stdout | from_json).Members | difference((result_task_org.stdout | from_json).Members) | map(attribute='TaskState') | list | first == "Completed") 30 | retries: 10 31 | delay: 20 32 | 33 | - name: Restart system power gracefully 34 | redfish_command: 35 | category: Systems 36 | command: PowerReboot 37 | baseuri: "{{ baseuri }}" 38 | username: "{{ username }}" 39 | password: "{{ password }}" 40 | timeout: 20 41 | register: power 42 | 43 | -------------------------------------------------------------------------------- /examples/config.ini: -------------------------------------------------------------------------------- 1 | [ConnectCfg] 2 | # BMC IP address(example:10.10.10.10) 3 | BmcIp = 4 | # BMC user name(example:USERID) 5 | BmcUsername = 6 | # BMC user password(example:PASSW0RD) 7 | # If you have special char '%' in password, '%' must be followed by '%' 8 | BmcUserpassword = 9 | # ComputerSystem instance id(None: first instance, All: all instances) 10 | SystemId = 11 | # Authentication mode(session or basic), the default is session 12 | Auth = session 13 | # Security certificate file for SSL connections, the default is null string 14 | Cafile = 15 | # BMC redfish accessing timeout seconds value, if not set, default value is 30 seconds 16 | Timeout = 17 | 18 | [FileServerCfg] 19 | ### FileServerCfg for "firmware update"/"mount virtual media"/"export ffdc" ### 20 | # File server protocol(example:SFTP) 21 | FSprotocol = 22 | # File server port(example:22) 23 | FSport = 24 | # File server ip(example:10.10.10.10) 25 | FSip = 26 | # File server user name(example:mysftp) 27 | FSusername = 28 | # File server user password(example:PASSW0RD) 29 | FSpassword = 30 | # File server path 31 | FSdir = 32 | 33 | ### FileServerCfg for SR635/SR655 server's "Bmc config backup"/"Bmc config restore" ### 34 | # http file server ip for SR635/SR655 35 | Httpip = 36 | # http file server port for SR635/SR655, default port is 80 37 | Httpport = 38 | # the directory on http file server for SR635/SR655 39 | Httpdir = 40 | -------------------------------------------------------------------------------- /examples/disable_secure_boot.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Disable secure boot 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2019 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import traceback 26 | import lenovo_utils as utils 27 | import json 28 | 29 | 30 | def disable_secure_boot(ip, login_account, login_password, system_id): 31 | """Disable secure boot 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :returns: returns enable secure boot result when succeeded or error message when failed 41 | """ 42 | result = {} 43 | login_host = 'https://' + ip 44 | try: 45 | # Connect using the BMC address, account name, and password 46 | # Create a REDFISH object 47 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 48 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 49 | # Login into the server and create a session 50 | REDFISH_OBJ.login(auth=utils.g_AUTH) 51 | except: 52 | traceback.print_exc() 53 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 54 | return result 55 | # GET the ComputerSystem resource 56 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 57 | if not system: 58 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 59 | REDFISH_OBJ.logout() 60 | return result 61 | 62 | for i in range(len(system)): 63 | system_url = system[i] 64 | response_system_url = REDFISH_OBJ.get(system_url, None) 65 | if response_system_url.status != 200: 66 | error_message = utils.get_extended_error(response_system_url) 67 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 68 | system_url, response_system_url.status, error_message)} 69 | REDFISH_OBJ.logout() 70 | return result 71 | 72 | if 'SecureBoot' in response_system_url.dict: 73 | # Get the SecureBoot resource url 74 | secureboot_url = response_system_url.dict['SecureBoot']['@odata.id'] 75 | # get etag to set If-Match precondition 76 | response_secureboot_url = REDFISH_OBJ.get(secureboot_url, None) 77 | if response_secureboot_url.status != 200: 78 | error_message = utils.get_extended_error(response_secureboot_url) 79 | result = {'ret': False, 'msg': "Url '%s' get failed. response Error code %s \nerror_message: %s" % ( 80 | secureboot_url, response_secureboot_url.status, error_message)} 81 | return result 82 | if "@odata.etag" in response_secureboot_url.dict: 83 | etag = response_secureboot_url.dict['@odata.etag'] 84 | else: 85 | etag = "*" 86 | headers = {"If-Match": etag} 87 | 88 | # perform patch to Disable secure boot 89 | secure_boot_enable = False 90 | parameter = {"SecureBootEnable": secure_boot_enable} 91 | response_secureboot = REDFISH_OBJ.patch(secureboot_url, body=parameter, headers=headers) 92 | if response_secureboot.status in [200,204]: 93 | result = {'ret': True, 94 | 'msg': "PATCH command successfully completed. SecureBootEnable has been set to False, it will take effect after system reboot."} 95 | else: 96 | error_message = utils.get_extended_error(response_secureboot) 97 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 98 | secureboot_url, response_secureboot.status, error_message)} 99 | try: 100 | REDFISH_OBJ.logout() 101 | except: 102 | pass 103 | return result 104 | 105 | result = {'ret': False, 'msg': "Not support SecureBoot"} 106 | try: 107 | REDFISH_OBJ.logout() 108 | except: 109 | pass 110 | return result 111 | 112 | 113 | if __name__ == '__main__': 114 | # Get parameters from config.ini and/or command line 115 | argget = utils.create_common_parameter_list() 116 | args = argget.parse_args() 117 | parameter_info = utils.parse_parameter(args) 118 | 119 | # Get connection info from the parameters user specified 120 | ip = parameter_info['ip'] 121 | login_account = parameter_info["user"] 122 | login_password = parameter_info["passwd"] 123 | system_id = parameter_info['sysid'] 124 | 125 | # Get disable secure boot result and check result 126 | result = disable_secure_boot(ip, login_account, login_password, system_id) 127 | if result['ret'] is True: 128 | del result['ret'] 129 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 130 | else: 131 | sys.stderr.write(result['msg'] + '\n') 132 | sys.exit(1) 133 | -------------------------------------------------------------------------------- /examples/firmware_startupdate.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Firmware start update 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2023 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | 30 | def firmware_startupdate(ip, login_account, login_password): 31 | """Firmware start update 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :returns: returns firmware start updating result 39 | """ 40 | # Connect using the address, account name, and password 41 | login_host = "https://" + ip 42 | try: 43 | # Create a REDFISH object 44 | result = {} 45 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 46 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 47 | REDFISH_OBJ.login(auth=utils.g_AUTH) 48 | except: 49 | traceback.print_exc() 50 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 51 | return result 52 | 53 | try: 54 | # Get ServiceRoot resource 55 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 56 | # Get response_update_service_url 57 | if response_base_url.status == 200: 58 | update_service_url = response_base_url.dict['UpdateService']['@odata.id'] 59 | else: 60 | message = utils.get_extended_error(response_base_url) 61 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ('/redfish/v1', response_base_url.status, message)} 62 | return result 63 | 64 | response_update_service_url = REDFISH_OBJ.get(update_service_url, None) 65 | if response_update_service_url.status == 200: 66 | # Start update firmware 67 | if "#UpdateService.StartUpdate" in response_update_service_url.dict['Actions']: 68 | start_update_url = response_update_service_url.dict['Actions']['#UpdateService.StartUpdate']['target'] 69 | # Build an dictionary to store the request body 70 | body = {} 71 | start_update_response = REDFISH_OBJ.post(start_update_url, body=body) 72 | response_code = start_update_response.status 73 | if response_code in [200, 204]: 74 | result = {'ret': True, 'msg': "Start update firmware successfully"} 75 | return result 76 | else: 77 | message = utils.get_extended_error(start_update_response) 78 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 79 | start_update_url, response_code, message)} 80 | return result 81 | else: 82 | result = {'ret': False, 'msg': "No resource found, not support start update action."} 83 | return result 84 | else: 85 | message = utils.get_extended_error(response_update_service_url) 86 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % (update_service_url, response_update_service_url.status, message)} 87 | return result 88 | except Exception as e: 89 | traceback.print_exc() 90 | result = {'ret': False, 'msg': "error_message: %s" % (e)} 91 | finally: 92 | # Logout of the current session 93 | try: 94 | REDFISH_OBJ.logout() 95 | except: 96 | pass 97 | return result 98 | 99 | if __name__ == '__main__': 100 | argget = utils.create_common_parameter_list() 101 | args = argget.parse_args() 102 | parameter_info = utils.parse_parameter(args) 103 | 104 | # Get connection info from the parameters user specified 105 | ip = parameter_info['ip'] 106 | login_account = parameter_info["user"] 107 | login_password = parameter_info["passwd"] 108 | 109 | # Firmware start update result and check result 110 | result = firmware_startupdate(ip, login_account, login_password) 111 | if result['ret'] is True: 112 | del result['ret'] 113 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 114 | else: 115 | sys.stderr.write(result['msg'] + '\n') 116 | sys.exit(1) 117 | -------------------------------------------------------------------------------- /examples/get_all_tasks.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get all tasks 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2020 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | def get_all_tasks(ip, login_account, login_password): 29 | """Get all tasks 30 | :params ip: BMC IP address 31 | :type ip: string 32 | :params login_account: BMC user name 33 | :type login_account: string 34 | :params login_password: BMC user password 35 | :type login_password: string 36 | :returns: returns all tasks' result when succeeded or error message when failed 37 | """ 38 | 39 | result = {} 40 | login_host = "https://" + ip 41 | 42 | # Connect using the BMC address, account name, and password 43 | # Create a REDFISH object 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth=utils.g_AUTH) 50 | except Exception as e: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 53 | return result 54 | 55 | # Get ServiceBase resource 56 | try: 57 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 58 | if response_base_url.status == 200: 59 | taskservice_url = response_base_url.dict["Tasks"]["@odata.id"] 60 | response_taskservice_url = REDFISH_OBJ.get(taskservice_url,None) 61 | if response_taskservice_url.status == 200: 62 | tasks_url = response_taskservice_url.dict["Tasks"]["@odata.id"] 63 | response_tasks_url = REDFISH_OBJ.get(tasks_url,None) 64 | if response_tasks_url.status == 200: 65 | dict_tasks = {} 66 | for key in response_tasks_url.dict: 67 | if key.startswith("@") or key == "Members@odata.navigationLink" or key == "Members": 68 | continue 69 | dict_tasks[key] = response_tasks_url.dict[key] 70 | list_member = [] 71 | for item in response_tasks_url.dict["Members"]: 72 | sub_url = item["@odata.id"] 73 | sub_url_response = REDFISH_OBJ.get(sub_url,None) 74 | if sub_url_response.status in [200, 202]: 75 | tmpdict = {} 76 | for key in sub_url_response.dict: 77 | if key.startswith("@"): 78 | continue 79 | else: 80 | tmpdict[key] = sub_url_response.dict[key] 81 | list_member.append(tmpdict) 82 | else: 83 | error_message = utils.get_extended_error(sub_url_response) 84 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 85 | sub_url, sub_url_response.status, error_message)} 86 | return result 87 | dict_tasks["Members"] = list_member 88 | result = {"ret":True,"entries":dict_tasks} 89 | return result 90 | else: 91 | error_message = utils.get_extended_error(response_tasks_url) 92 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 93 | tasks_url, response_tasks_url.status, error_message)} 94 | return result 95 | else: 96 | error_message = utils.get_extended_error(response_taskservice_url) 97 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 98 | taskservice_url, response_taskservice_url.status, error_message)} 99 | return result 100 | else: 101 | error_message = utils.get_extended_error(response_base_url) 102 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 103 | '/redfish/v1', response_base_url.status, error_message)} 104 | return result 105 | except Exception as e: 106 | traceback.print_exc() 107 | result = {'ret': False, 'msg': "Exception msg %s" % e} 108 | return result 109 | finally: 110 | try: 111 | REDFISH_OBJ.logout() 112 | except: 113 | pass 114 | 115 | if __name__ == '__main__': 116 | # Get parameters from config.ini and/or command line 117 | argget = utils.create_common_parameter_list() 118 | args = argget.parse_args() 119 | parameter_info = utils.parse_parameter(args) 120 | 121 | # Get connection info from the parameters user specified 122 | ip = parameter_info['ip'] 123 | login_account = parameter_info["user"] 124 | login_password = parameter_info["passwd"] 125 | 126 | # Get all tasks and check result 127 | result = get_all_tasks(ip, login_account, login_password) 128 | if result['ret'] is True: 129 | del result['ret'] 130 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 131 | else: 132 | sys.stderr.write(result['msg'] + '\n') 133 | sys.exit(1) 134 | -------------------------------------------------------------------------------- /examples/get_bios_attribute.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get Bios attribute 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | 24 | import sys 25 | import json 26 | import redfish 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def get_bios_attribute(ip, login_account, login_password, system_id, attribute_name): 32 | """get bios attribute by user specified 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 40 | :type system_id: None or string 41 | :params attribute_name: Bios attribute name by user specified 42 | :type attribute_name: string 43 | :returns: returns get bios attribute value when succeeded or error message when failed 44 | """ 45 | result = {} 46 | try: 47 | # Connect using the BMC address, account name, and password 48 | # Create a REDFISH object 49 | login_host = "https://" + ip 50 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 51 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 52 | # Login into the server and create a session 53 | REDFISH_OBJ.login(auth=utils.g_AUTH) 54 | except: 55 | traceback.print_exc() 56 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 57 | return result 58 | 59 | try: 60 | # GET the ComputerSystem resource 61 | system = utils.get_system_url("/redfish/v1",system_id, REDFISH_OBJ) 62 | if not system: 63 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 64 | return result 65 | 66 | for i in range(len(system)): 67 | system_url = system[i] 68 | response_system_url = REDFISH_OBJ.get(system_url, None) 69 | if response_system_url.status == 200: 70 | # Get the ComputerBios resource 71 | bios_url = response_system_url.dict['Bios']['@odata.id'] 72 | else: 73 | error_message = utils.get_extended_error(response_system_url) 74 | result = {'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % ( 75 | system_url, response_system_url.status, error_message)} 76 | return result 77 | 78 | response_bios_url = REDFISH_OBJ.get(bios_url, None) 79 | if response_bios_url.status == 200: 80 | attribute = response_bios_url.dict['Attributes'] 81 | bios_attribute = {} 82 | if attribute_name in attribute.keys(): 83 | bios_attribute[attribute_name] = attribute[attribute_name] 84 | result = {'ret': True, 'msg': bios_attribute} 85 | else: 86 | result = {'ret': False, 'msg': " No this attribute in the bios attribute"} 87 | elif response_bios_url.status == 400: 88 | result = {'ret': False, 'msg': 'Not supported on this platform'} 89 | REDFISH_OBJ.logout() 90 | return result 91 | else: 92 | error_message = utils.get_extended_error(response_bios_url) 93 | result = {'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % ( 94 | bios_url, response_bios_url.status, error_message)} 95 | return result 96 | except Exception as e: 97 | traceback.print_exc() 98 | result = {'ret': False, 'msg': "error message %s" % e} 99 | finally: 100 | # Logout of the current session 101 | try: 102 | REDFISH_OBJ.logout() 103 | except: 104 | pass 105 | return result 106 | 107 | 108 | def add_helpmessage(parser): 109 | parser.add_argument('--name', type=str, required=True, help='Input the attribute name') 110 | 111 | 112 | def add_parameter(): 113 | """Add parameter""" 114 | argget = utils.create_common_parameter_list() 115 | add_helpmessage(argget) 116 | args = argget.parse_args() 117 | parameter_info = utils.parse_parameter(args) 118 | parameter_info['attribute_name'] = args.name 119 | return parameter_info 120 | 121 | 122 | if __name__ == '__main__': 123 | # Get parameters from config.ini and/or command line 124 | parameter_info = add_parameter() 125 | # Get connection info from the parameters user specified 126 | ip = parameter_info['ip'] 127 | login_account = parameter_info["user"] 128 | login_password = parameter_info["passwd"] 129 | system_id = parameter_info['sysid'] 130 | 131 | # Get search attribute from the parameters user specified 132 | try: 133 | attribute_name = parameter_info['attribute_name'] 134 | except: 135 | sys.stderr.write("Please run the command 'python %s -h' to view the help info" % sys.argv[0]) 136 | sys.exit(1) 137 | 138 | # Get bios sttribute value and check result 139 | result = get_bios_attribute(ip, login_account, login_password,system_id, attribute_name) 140 | if result['ret'] is True: 141 | del result['ret'] 142 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 143 | else: 144 | sys.stderr.write(result['msg'] + '\n') 145 | sys.exit(1) 146 | -------------------------------------------------------------------------------- /examples/get_bios_bootmode.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Lenovo Redfish examples - Get bios boot mode 3 | # 4 | # Copyright Notice: 5 | # 6 | # Copyright 2018 Lenovo Corporation 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 9 | # not use this file except in compliance with the License. You may obtain 10 | # a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 17 | # License for the specific language governing permissions and limitations 18 | # under the License. 19 | ### 20 | 21 | 22 | import sys 23 | import json 24 | import redfish 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def get_bios_bootmode(ip, login_account, login_password, system_id): 30 | """Get bios boot mode 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 38 | :type system_id: None or string 39 | :returns: returns bios boot mode when succeeded or error message when failed 40 | """ 41 | result = {} 42 | login_host = "https://" + ip 43 | try: 44 | # Connect using the BMC address, account name, and password 45 | # Create a REDFISH object 46 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 47 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 48 | # Login into the server and create a session 49 | REDFISH_OBJ.login(auth=utils.g_AUTH) 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 53 | return result 54 | 55 | try: 56 | # GET the ComputerSystem resource 57 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 58 | if not system: 59 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 60 | return result 61 | 62 | for i in range(len(system)): 63 | system_url = system[i] 64 | response_system_url = REDFISH_OBJ.get(system_url, None) 65 | if response_system_url.status == 200: 66 | # Get the bios resource 67 | bios_url = response_system_url.dict['Bios']['@odata.id'] 68 | response_bios_url = REDFISH_OBJ.get(bios_url, None) 69 | if response_bios_url.status != 200: 70 | error_message = utils.get_extended_error(response_bios_url) 71 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (bios_url, response_bios_url.status, error_message)} 72 | return result 73 | else: # Get bios success 74 | # Seek boot mode from bios attributes 75 | attribute_bootmode = None 76 | attributes = response_bios_url.dict['Attributes'] 77 | for attribute in attributes: 78 | if attribute == "BootMode" or attribute == "SystemBootMode": 79 | attribute_bootmode = attribute 80 | if attribute_bootmode == None: 81 | for attribute in attributes: 82 | if "SystemBootMode" in attribute: 83 | attribute_bootmode = attribute 84 | if attribute_bootmode == None: 85 | for attribute in attributes: 86 | if "Boot Mode" in attribute or "Boot_Mode" in attribute: 87 | attribute_bootmode = attribute 88 | if attribute_bootmode == None: 89 | result = {'ret': False, 'msg': "Can not found BootMode attribute in response of url %s" %(bios_url)} 90 | return result 91 | # Set output 92 | boot_mode_dict = {} 93 | boot_mode = response_bios_url.dict['Attributes'][attribute_bootmode] 94 | boot_mode_dict["BootMode"] = boot_mode 95 | result = {"ret": True, "msg":boot_mode_dict} 96 | return result 97 | else: 98 | error_message = utils.get_extended_error(response_system_url) 99 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (system_url, response_system_url.status, error_message)} 100 | return result 101 | 102 | except Exception as e: 103 | traceback.print_exc() 104 | result = {'ret':False, 'msg':"error_message:%s" %(e)} 105 | finally: 106 | # Logout of the current session 107 | try: 108 | REDFISH_OBJ.logout() 109 | except: 110 | pass 111 | return result 112 | 113 | 114 | if __name__ == '__main__': 115 | # Get parameters from config.ini and/or command line 116 | argget = utils.create_common_parameter_list() 117 | args = argget.parse_args() 118 | parameter_info = utils.parse_parameter(args) 119 | 120 | # Get connection info from the parameters user specified 121 | ip = parameter_info['ip'] 122 | login_account = parameter_info["user"] 123 | login_password = parameter_info["passwd"] 124 | system_id = parameter_info['sysid'] 125 | 126 | # Get boot mode information and check result 127 | result = get_bios_bootmode(ip, login_account, login_password, system_id) 128 | if result['ret'] is True: 129 | del result['ret'] 130 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 131 | else: 132 | sys.stderr.write(result['msg'] + '\n') 133 | sys.exit(1) 134 | -------------------------------------------------------------------------------- /examples/get_bmc_ntp.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get bmc ntp 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | def get_bmc_ntp(ip, login_account, login_password): 29 | """Get bmc ntp 30 | :params ip: BMC IP address 31 | :type ip: string 32 | :params login_account: BMC user name 33 | :type login_account: string 34 | :params login_password: BMC user password 35 | :type login_password: string 36 | :returns: returns Get bmc ntp result when succeeded or error message when failed 37 | """ 38 | 39 | result = {} 40 | login_host = "https://" + ip 41 | 42 | # Connect using the BMC address, account name, and password 43 | # Create a REDFISH object 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth=utils.g_AUTH) 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 53 | return result 54 | # Get ServiceBase resource 55 | try: 56 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 57 | # Get response_base_url 58 | if response_base_url.status == 200: 59 | managers_url = response_base_url.dict['Managers']['@odata.id'] 60 | else: 61 | error_message = utils.get_extended_error(response_base_url) 62 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 63 | '/redfish/v1', response_base_url.status, error_message)} 64 | return result 65 | response_managers_url = REDFISH_OBJ.get(managers_url, None) 66 | if response_managers_url.status == 200: 67 | #Get NTP info 68 | list_rt_ntp = [] 69 | for request in response_managers_url.dict['Members']: 70 | request_url = request['@odata.id'] 71 | response_url = REDFISH_OBJ.get(request_url, None) 72 | if response_url.status == 200: 73 | if "NetworkProtocol" in response_url.dict: 74 | network_url = response_url.dict["NetworkProtocol"]['@odata.id'] 75 | response_network_url = REDFISH_OBJ.get(network_url, None) 76 | if response_network_url.status == 200: 77 | if "NTP" in response_network_url.dict and "NTPServers" in response_network_url.dict["NTP"]: 78 | list_ntp_server = response_network_url.dict["NTP"]["NTPServers"] 79 | list_rt_ntp.append(list_ntp_server) 80 | else: 81 | error_message = utils.get_extended_error(response_network_url) 82 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 83 | network_url, response_network_url.status, error_message)} 84 | return result 85 | else: 86 | error_message = utils.get_extended_error(response_url) 87 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 88 | request_url, response_url.status, error_message)} 89 | return result 90 | result["ret"] = True 91 | result["entries"] = list_rt_ntp 92 | return result 93 | else: 94 | error_message = utils.get_extended_error(response_managers_url) 95 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 96 | managers_url, response_managers_url.status, error_message)} 97 | return result 98 | except Exception as e: 99 | traceback.print_exc() 100 | result = {'ret': False, 'msg': 'exception msg %s' % e} 101 | return result 102 | finally: 103 | try: 104 | REDFISH_OBJ.logout() 105 | except: 106 | pass 107 | 108 | 109 | if __name__ == '__main__': 110 | # Get parameters from config.ini and/or command line 111 | argget = utils.create_common_parameter_list() 112 | args = argget.parse_args() 113 | parameter_info = utils.parse_parameter(args) 114 | 115 | # Get connection info from the parameters user specified 116 | ip = parameter_info['ip'] 117 | login_account = parameter_info["user"] 118 | login_password = parameter_info["passwd"] 119 | 120 | # Get bmc ntp and check result 121 | result = get_bmc_ntp(ip, login_account, login_password) 122 | if result['ret'] is True: 123 | del result['ret'] 124 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 125 | else: 126 | sys.stderr.write(result['msg'] + '\n') 127 | sys.exit(1) 128 | -------------------------------------------------------------------------------- /examples/get_chassis_indicator_led.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - get chassis indicator led 4 | # Copyright Notice: 5 | # 6 | # Copyright 2018 Lenovo Corporation 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 9 | # not use this file except in compliance with the License. You may obtain 10 | # a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 17 | # License for the specific language governing permissions and limitations 18 | # under the License. 19 | ### 20 | 21 | 22 | import redfish 23 | import sys 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def get_chassis_indicator_led(ip, login_account, login_password): 30 | """Get chassis indicator led 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns get chassis indicator led status when succeeded or error message when failed 38 | """ 39 | result = {} 40 | login_host = "https://" + ip 41 | try: 42 | # Connect using the BMC address, account name, and password 43 | # Create a REDFISH object 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | # Login into the server and create a session 47 | REDFISH_OBJ.login(auth=utils.g_AUTH) 48 | except: 49 | traceback.print_exc() 50 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 51 | return result 52 | 53 | try: 54 | # Get ComputerBase resource 55 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 56 | # Get response_base_url 57 | if response_base_url.status == 200: 58 | chassis_url = response_base_url.dict['Chassis']['@odata.id'] 59 | else: 60 | error_message = utils.get_extended_error(response_base_url) 61 | result = {'ret': False, 'msg': "Url '/redfish/v1' response Error code %s \nerror_message: %s" % ( 62 | response_base_url.status, error_message)} 63 | return result 64 | 65 | # Get response chassis url resource 66 | response_chassis_url = REDFISH_OBJ.get(chassis_url, None) 67 | if response_chassis_url.status == 200: 68 | # Get the LED status 69 | for i in range(response_chassis_url.dict['Members@odata.count']): 70 | led_status = {} 71 | led_url = response_chassis_url.dict['Members'][i]['@odata.id'] 72 | response_led_url = REDFISH_OBJ.get(led_url, None) 73 | if response_led_url.status == 200: 74 | if response_chassis_url.dict['Members@odata.count'] > 1 and 'IndicatorLED' not in response_led_url.dict: 75 | continue 76 | led_status["indicatorLED"] = response_led_url.dict['IndicatorLED'] 77 | result = {'ret': True, 'msg': led_status} 78 | return result 79 | else: 80 | error_message = utils.get_extended_error(response_led_url) 81 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 82 | led_url, response_led_url.status, error_message)} 83 | return result 84 | else: 85 | error_message = utils.get_extended_error(response_chassis_url) 86 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (chassis_url, response_chassis_url.status, error_message)} 87 | return result 88 | 89 | except Exception as e: 90 | traceback.print_exc() 91 | result = {'ret': False, 'msg': "error_message: %s" % e} 92 | finally: 93 | # Logout of the current session 94 | try: 95 | REDFISH_OBJ.logout() 96 | except: 97 | pass 98 | return result 99 | 100 | 101 | if __name__ == '__main__': 102 | # Get parameters from config.ini and/or command line 103 | argget = utils.create_common_parameter_list() 104 | args = argget.parse_args() 105 | parameter_info = utils.parse_parameter(args) 106 | 107 | # Get connection info from the parameters user specified 108 | ip = parameter_info['ip'] 109 | login_account = parameter_info["user"] 110 | login_password = parameter_info["passwd"] 111 | 112 | # Get chassis indicator led and check result 113 | result = get_chassis_indicator_led(ip, login_account, login_password) 114 | if result['ret'] is True: 115 | del result['ret'] 116 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 117 | else: 118 | sys.stderr.write(result['msg'] + '\n') 119 | sys.exit(1) 120 | -------------------------------------------------------------------------------- /examples/get_chassis_inventory.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - get chassis inventory 4 | # Copyright Notice: 5 | # 6 | # Copyright 2021 Lenovo Corporation 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 9 | # not use this file except in compliance with the License. You may obtain 10 | # a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 17 | # License for the specific language governing permissions and limitations 18 | # under the License. 19 | ### 20 | 21 | 22 | import redfish 23 | import sys 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def get_chassis_inventory(ip, login_account, login_password): 30 | """Get chassis inventory 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns get chassis inventory when succeeded or error message when failed 38 | """ 39 | result = {} 40 | login_host = "https://" + ip 41 | try: 42 | # Connect using the BMC address, account name, and password 43 | # Create a REDFISH object 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | # Login into the server and create a session 47 | REDFISH_OBJ.login(auth=utils.g_AUTH) 48 | except: 49 | traceback.print_exc() 50 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 51 | return result 52 | 53 | try: 54 | chassis_details = [] 55 | # Get ComputerBase resource 56 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 57 | # Get response_base_url 58 | if response_base_url.status == 200: 59 | chassis_url = response_base_url.dict['Chassis']['@odata.id'] 60 | else: 61 | error_message = utils.get_extended_error(response_base_url) 62 | result = {'ret': False, 'msg': "Url '/redfish/v1' response Error code %s \nerror_message: %s" % ( 63 | response_base_url.status, error_message)} 64 | return result 65 | 66 | # Get response chassis url resource 67 | response_chassis_url = REDFISH_OBJ.get(chassis_url, None) 68 | if response_chassis_url.status == 200: 69 | # Get the chassis information 70 | for i in range(response_chassis_url.dict['Members@odata.count']): 71 | chassis_1_url = response_chassis_url.dict['Members'][i]['@odata.id'] 72 | response_chassis_1_url = REDFISH_OBJ.get(chassis_1_url, None) 73 | if response_chassis_1_url.status == 200: 74 | # if chassis is not normal skip it 75 | if response_chassis_url.dict['Members@odata.count'] > 1 and \ 76 | ("Links" not in response_chassis_1_url.dict or 77 | "ComputerSystems" not in response_chassis_1_url.dict["Links"] or 78 | 'Location' not in response_chassis_1_url.dict): 79 | continue 80 | chassis_inventory = response_chassis_1_url.dict 81 | # Delete content with only url property 82 | for property in ["Links", "@odata.etag", "@odata.id", "@odata.type", "LogServices", 83 | "Memory", "NetworkAdapters", "PCIeDevices", "PCIeSlots", "Power", "Thermal", 84 | "Controls", "EnvironmentMetrics", "PowerSubsystem", "Sensors", "ThermalSubsystem"]: 85 | if property in chassis_inventory: 86 | del chassis_inventory[property] 87 | if "Oem" in chassis_inventory and "Lenovo" in chassis_inventory["Oem"]: 88 | for property in ["LEDs", "Sensors", "Slots", "@odata.type"]: 89 | if property in chassis_inventory["Oem"]["Lenovo"]: 90 | del chassis_inventory["Oem"]["Lenovo"][property] 91 | 92 | chassis_details.append(chassis_inventory) 93 | result = {'ret': True, 'msg': chassis_details} 94 | return result 95 | else: 96 | error_message = utils.get_extended_error(response_chassis_1_url) 97 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 98 | chassis_1_url, response_chassis_1_url.status, error_message)} 99 | return result 100 | else: 101 | error_message = utils.get_extended_error(response_chassis_url) 102 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (chassis_url, response_chassis_url.status, error_message)} 103 | return result 104 | 105 | except Exception as e: 106 | traceback.print_exc() 107 | result = {'ret': False, 'msg': "error_message: %s" % e} 108 | finally: 109 | # Logout of the current session 110 | try: 111 | REDFISH_OBJ.logout() 112 | except: 113 | pass 114 | return result 115 | 116 | 117 | if __name__ == '__main__': 118 | # Get parameters from config.ini and/or command line 119 | argget = utils.create_common_parameter_list() 120 | args = argget.parse_args() 121 | parameter_info = utils.parse_parameter(args) 122 | 123 | # Get connection info from the parameters user specified 124 | ip = parameter_info['ip'] 125 | login_account = parameter_info["user"] 126 | login_password = parameter_info["passwd"] 127 | 128 | # Get chassis inventory and check result 129 | result = get_chassis_inventory(ip, login_account, login_password) 130 | if result['ret'] is True: 131 | del result['ret'] 132 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 133 | else: 134 | sys.stderr.write(result['msg'] + '\n') 135 | sys.exit(1) 136 | -------------------------------------------------------------------------------- /examples/get_cpu_inventory.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get the CPU information 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | 24 | import sys 25 | import json 26 | import redfish 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def get_cpu_inventory(ip, login_account, login_password, system_id): 32 | """Get cpu inventory 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 40 | :type system_id: None or string 41 | :returns: returns cpu inventory when succeeded or error message when failed 42 | """ 43 | result = {} 44 | login_host = "https://" + ip 45 | try: 46 | # Connect using the BMC address, account name, and password 47 | # Create a REDFISH object 48 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 49 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 50 | # Login into the server and create a session 51 | REDFISH_OBJ.login(auth=utils.g_AUTH) 52 | except Exception as e: 53 | traceback.print_exc() 54 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 55 | return result 56 | 57 | cpu_details = [] 58 | # GET the ComputerSystem resource 59 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 60 | if not system: 61 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 62 | REDFISH_OBJ.logout() 63 | return result 64 | 65 | for i in range(len(system)): 66 | # Get Processors url 67 | system_url = system[i] 68 | response_system_url = REDFISH_OBJ.get(system_url, None) 69 | if response_system_url.status == 200: 70 | processors_url = response_system_url.dict['Processors']['@odata.id'] 71 | else: 72 | result = {'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status} 73 | REDFISH_OBJ.logout() 74 | return result 75 | 76 | # Get the Processors collection 77 | response_processors_url = REDFISH_OBJ.get(processors_url, None) 78 | if response_processors_url.status == 200: 79 | # Get Members url 80 | members_count = response_processors_url.dict['Members@odata.count'] 81 | else: 82 | result = {'ret': False, 'msg': "response_processors_url Error code %s" % response_processors_url.status} 83 | REDFISH_OBJ.logout() 84 | return result 85 | 86 | # Get each processor info 87 | for i in range(members_count): 88 | cpu = {} 89 | # Get members url resource 90 | members_url = response_processors_url.dict['Members'][i]['@odata.id'] 91 | response_members_url = REDFISH_OBJ.get(members_url, None) 92 | if response_members_url.status == 200: 93 | for property in ['Id', 'Name', 'TotalThreads', 'InstructionSet', 'Status', 'ProcessorType', 'ProcessorId', 'ProcessorMemory', 94 | 'ProcessorArchitecture', 'TotalCores', 'TotalEnabledCores', 'Manufacturer', 'MaxSpeedMHz', 'Model', 'Socket', 'TDPWatts']: 95 | if property in response_members_url.dict: 96 | cpu[property] = response_members_url.dict[property] 97 | cpu_details.append(cpu) 98 | else: 99 | result = {'ret': False, 'msg': "response_members_url Error code %s" % response_members_url.status} 100 | REDFISH_OBJ.logout() 101 | return result 102 | 103 | result['ret'] = True 104 | result['entries'] = cpu_details 105 | # Logout of the current session 106 | try: 107 | REDFISH_OBJ.logout() 108 | except: 109 | pass 110 | return result 111 | 112 | 113 | if __name__ == '__main__': 114 | # Get parameters from config.ini and/or command line 115 | argget = utils.create_common_parameter_list() 116 | args = argget.parse_args() 117 | parameter_info = utils.parse_parameter(args) 118 | 119 | # Get connection info from the parameters user specified 120 | ip = parameter_info['ip'] 121 | login_account = parameter_info["user"] 122 | login_password = parameter_info["passwd"] 123 | system_id = parameter_info['sysid'] 124 | 125 | # Get cpu inventory and check result 126 | result = get_cpu_inventory(ip, login_account, login_password, system_id) 127 | if result['ret'] is True: 128 | del result['ret'] 129 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 130 | else: 131 | sys.stderr.write(result['msg'] + '\n') 132 | sys.exit(1) 133 | -------------------------------------------------------------------------------- /examples/get_event_subscriptions.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get event subscriptions 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | def get_event_subscriptions(ip, login_account, login_password): 29 | """Get event subscriptions 30 | :params ip: BMC IP address 31 | :type ip: string 32 | :params login_account: BMC user name 33 | :type login_account: string 34 | :params login_password: BMC user password 35 | :type login_password: string 36 | :returns: returns Get event subscriptions result when succeeded or error message when failed 37 | """ 38 | 39 | result = {} 40 | login_host = "https://" + ip 41 | 42 | # Connect using the BMC address, account name, and password 43 | # Create a REDFISH object 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth=utils.g_AUTH) 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 53 | return result 54 | # Get ServiceBase resource 55 | try: 56 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 57 | if response_base_url.status == 200: 58 | event_url = response_base_url.dict["EventService"]["@odata.id"] 59 | response_event_url = REDFISH_OBJ.get(event_url,None) 60 | if response_event_url.status == 200: 61 | subscriptions_url = response_event_url.dict["Subscriptions"]["@odata.id"] 62 | response_subscriptions_url = REDFISH_OBJ.get(subscriptions_url,None) 63 | if response_subscriptions_url.status == 200: 64 | dict_subscriptions = {} 65 | for key in response_subscriptions_url.dict: 66 | if key.startswith("@") or key == "Members@odata.navigationLink" or key == "Members": 67 | continue 68 | dict_subscriptions[key] = response_subscriptions_url.dict[key] 69 | list_member = [] 70 | for item in response_subscriptions_url.dict["Members"]: 71 | sub_url = item["@odata.id"] 72 | sub_url_response = REDFISH_OBJ.get(sub_url,None) 73 | if sub_url_response.status == 200: 74 | tmpdict = {} 75 | for key in sub_url_response.dict: 76 | if key.startswith("@"): 77 | continue 78 | else: 79 | tmpdict[key] = sub_url_response.dict[key] 80 | list_member.append(tmpdict) 81 | else: 82 | error_message = utils.get_extended_error(sub_url_response) 83 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 84 | sub_url, sub_url_response.status, error_message)} 85 | return result 86 | dict_subscriptions["Members"] = list_member 87 | result = {"ret":True,"entries":dict_subscriptions} 88 | return result 89 | else: 90 | error_message = utils.get_extended_error(response_subscriptions_url) 91 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 92 | subscriptions_url, response_subscriptions_url.status, error_message)} 93 | return result 94 | else: 95 | error_message = utils.get_extended_error(response_event_url) 96 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 97 | event_url, response_event_url.status, error_message)} 98 | return result 99 | else: 100 | error_message = utils.get_extended_error(response_base_url) 101 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 102 | '/redfish/v1', response_base_url.status, error_message)} 103 | return result 104 | except Exception as e: 105 | traceback.print_exc() 106 | result = {'ret': False, 'msg': "Exception msg %s" % e} 107 | return result 108 | finally: 109 | try: 110 | REDFISH_OBJ.logout() 111 | except: 112 | pass 113 | 114 | if __name__ == '__main__': 115 | # Get parameters from config.ini and/or command line 116 | argget = utils.create_common_parameter_list() 117 | args = argget.parse_args() 118 | parameter_info = utils.parse_parameter(args) 119 | 120 | # Get connection info from the parameters user specified 121 | ip = parameter_info['ip'] 122 | login_account = parameter_info["user"] 123 | login_password = parameter_info["passwd"] 124 | 125 | # Get event subscriptions and check result 126 | result = get_event_subscriptions(ip, login_account, login_password) 127 | if result['ret'] is True: 128 | del result['ret'] 129 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 130 | else: 131 | sys.stderr.write(result['msg'] + '\n') 132 | sys.exit(1) 133 | -------------------------------------------------------------------------------- /examples/get_fw_inventory.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get FW inventory 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | def get_fw_inventory(ip, login_account, login_password): 30 | """Get BMC inventory 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns firmware inventory when succeeded or error message when failed 38 | """ 39 | result = {} 40 | try: 41 | # Connect using the BMC address, account name, and password 42 | # Create a REDFISH object 43 | login_host = "https://" + ip 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | # Login into the server and create a session 47 | REDFISH_OBJ.login(auth=utils.g_AUTH) 48 | except: 49 | traceback.print_exc() 50 | result = {'ret': False, 'msg': "Please check if the username, password, IP is correct."} 51 | return result 52 | 53 | fw_version = [] 54 | # Get ServiceRoot resource 55 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 56 | # Get response_update_service_url 57 | if response_base_url.status == 200: 58 | update_service_url = response_base_url.dict['UpdateService']['@odata.id'] 59 | else: 60 | result = {'ret': False, 'msg': "response base url Error code %s" % response_base_url.status} 61 | REDFISH_OBJ.logout() 62 | return result 63 | 64 | response_update_service_url = REDFISH_OBJ.get(update_service_url, None) 65 | if response_update_service_url.status == 200: 66 | firmware_inventory_url = response_update_service_url.dict['FirmwareInventory']['@odata.id'] 67 | response_firmware_url = REDFISH_OBJ.get(firmware_inventory_url, None) 68 | if response_firmware_url.status == 200: 69 | for firmware_url in response_firmware_url.dict["Members"]: 70 | firmware_version_url = firmware_url['@odata.id'] 71 | firmware_list = firmware_version_url.split("/") 72 | response_firmware_version = REDFISH_OBJ.get(firmware_version_url, None) 73 | if response_firmware_version.status == 200: 74 | fw = {} 75 | for property in ['Version', 'SoftwareId', 'Description', 'Status']: 76 | if property in response_firmware_version.dict: 77 | fw[property] = response_firmware_version.dict[property] 78 | fw = {firmware_list[-1]: fw} 79 | fw_version.append(fw) 80 | else: 81 | result = {'ret': False, 82 | 'msg': "response firmware version Error code %s" % response_firmware_version.status} 83 | REDFISH_OBJ.logout() 84 | return result 85 | else: 86 | result = {'ret': False, 'msg': "response firmware url Error code %s" % response_firmware_url.status} 87 | REDFISH_OBJ.logout() 88 | return result 89 | else: 90 | result = {'ret': False, 'msg': "response update service_url Error code %s" % response_update_service_url.status} 91 | REDFISH_OBJ.logout() 92 | return result 93 | 94 | result['ret'] = True 95 | result['fw_version_detail'] = fw_version 96 | 97 | try: 98 | REDFISH_OBJ.logout() 99 | except: 100 | pass 101 | return result 102 | 103 | 104 | def add_parameter(): 105 | """Add parameter""" 106 | argget = utils.create_common_parameter_list() 107 | args = argget.parse_args() 108 | parameter_info = utils.parse_parameter(args) 109 | return parameter_info 110 | 111 | 112 | 113 | if __name__ == '__main__': 114 | # Get parameters from config.ini and/or command line 115 | parameter_info = add_parameter() 116 | 117 | # Get connection info from the parameters user specified 118 | ip = parameter_info['ip'] 119 | login_account = parameter_info["user"] 120 | login_password = parameter_info["passwd"] 121 | 122 | # Get firmware inventory and check result 123 | result = get_fw_inventory(ip, login_account, login_password) 124 | 125 | if result['ret'] is True: 126 | del result['ret'] 127 | sys.stdout.write(json.dumps(result['fw_version_detail'], sort_keys=True, indent=2) + '\n') 128 | else: 129 | sys.stderr.write(result['msg'] + '\n') 130 | sys.exit(1) 131 | -------------------------------------------------------------------------------- /examples/get_power_state.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get the current System Boot Once target 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import json 25 | import redfish 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | 30 | def get_power_state(ip, login_account, login_password, system_id): 31 | """Get power state 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :returns: returns power state when succeeded or error message when failed 41 | """ 42 | result = {} 43 | login_host = "https://" + ip 44 | try: 45 | # Connect using the BMC address, account name, and password 46 | # Create a REDFISH object 47 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 48 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 49 | # Login into the server and create a session 50 | REDFISH_OBJ.login(auth=utils.g_AUTH) 51 | except: 52 | traceback.print_exc() 53 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 54 | return result 55 | # GET the ComputerSystem resource 56 | power_details = [] 57 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 58 | if not system: 59 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 60 | REDFISH_OBJ.logout() 61 | return result 62 | for i in range(len(system)): 63 | system_url = system[i] 64 | response_system_url = REDFISH_OBJ.get(system_url, None) 65 | if response_system_url.status == 200: 66 | # Get the response 67 | power_state = {} 68 | # Get the PowerState property 69 | PowerState = response_system_url.dict["PowerState"] 70 | power_state["PowerState"] = PowerState 71 | power_details.append(power_state) 72 | else: 73 | result = {'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status} 74 | REDFISH_OBJ.logout() 75 | return result 76 | 77 | result['ret'] = True 78 | result['entries'] = power_details 79 | # Logout of the current session 80 | try: 81 | REDFISH_OBJ.logout() 82 | except: 83 | pass 84 | return result 85 | 86 | 87 | if __name__ == '__main__': 88 | # Get parameters from config.ini and/or command line 89 | argget = utils.create_common_parameter_list() 90 | args = argget.parse_args() 91 | parameter_info = utils.parse_parameter(args) 92 | 93 | # Get connection info from the parameters user specified 94 | ip = parameter_info['ip'] 95 | login_account = parameter_info["user"] 96 | login_password = parameter_info["passwd"] 97 | system_id = parameter_info['sysid'] 98 | 99 | # Get power state and check result 100 | result = get_power_state(ip, login_account, login_password, system_id) 101 | if result['ret'] is True: 102 | del result['ret'] 103 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 104 | else: 105 | sys.stderr.write(result['msg'] + '\n') 106 | sys.exit(1) 107 | -------------------------------------------------------------------------------- /examples/get_secure_boot_status.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get secure boot status 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import traceback 26 | import lenovo_utils as utils 27 | import json 28 | 29 | 30 | def get_secure_boot_status(ip, login_account, login_password, system_id): 31 | """Get secure boot status 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :returns: returns secure boot status when succeeded or error message when failed 41 | """ 42 | result = {} 43 | login_host = "https://" + ip 44 | try: 45 | # Connect using the BMC address, account name, and password 46 | # Create a REDFISH object 47 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 48 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 49 | # Login into the server and create a session 50 | REDFISH_OBJ.login(auth=utils.g_AUTH) 51 | except: 52 | traceback.print_exc() 53 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 54 | return result 55 | 56 | # GET the ComputerSystem resource 57 | secure_details = [] 58 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 59 | if not system: 60 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 61 | REDFISH_OBJ.logout() 62 | return result 63 | for i in range(len(system)): 64 | system_url = system[i] 65 | response_system_url = REDFISH_OBJ.get(system_url, None) 66 | if response_system_url.status != 200: 67 | error_message = utils.get_extended_error(response_system_url) 68 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 69 | system_url, response_system_url.status, error_message)} 70 | REDFISH_OBJ.logout() 71 | return result 72 | 73 | if 'SecureBoot' not in response_system_url.dict: 74 | continue 75 | 76 | secure_boot_url = response_system_url.dict['SecureBoot']['@odata.id'] 77 | # Get the secure boot url resource 78 | response_secure_boot_url = REDFISH_OBJ.get(secure_boot_url, None) 79 | if response_secure_boot_url.status == 200: 80 | secure = {} 81 | secure_boot_enable = response_secure_boot_url.dict["SecureBootEnable"] 82 | secure_boot_mode = response_secure_boot_url.dict["SecureBootMode"] 83 | secure['SecureBootEnable'] = secure_boot_enable 84 | secure['SecureBootMode'] = secure_boot_mode 85 | secure_details.append(secure) 86 | else: 87 | error_message = utils.get_extended_error(response_secure_boot_url) 88 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 89 | secure_boot_url, response_secure_boot_url.status, error_message)} 90 | REDFISH_OBJ.logout() 91 | return result 92 | 93 | if len(secure_details) == 0: 94 | result = {'ret': False, 'msg': "Not support SecureBoot"} 95 | else: 96 | result['ret'] = True 97 | result['entries'] = secure_details 98 | # Logout of the current session 99 | try: 100 | REDFISH_OBJ.logout() 101 | except: 102 | pass 103 | return result 104 | 105 | 106 | if __name__ == '__main__': 107 | # Get parameters from config.ini and/or command line 108 | argget = utils.create_common_parameter_list() 109 | args = argget.parse_args() 110 | parameter_info = utils.parse_parameter(args) 111 | 112 | # Get connection info from the parameters user specified 113 | ip = parameter_info['ip'] 114 | login_account = parameter_info["user"] 115 | login_password = parameter_info["passwd"] 116 | system_id = parameter_info['sysid'] 117 | 118 | # Get secure boot status and check result 119 | result = get_secure_boot_status(ip, login_account, login_password, system_id) 120 | 121 | if result['ret'] is True: 122 | del result['ret'] 123 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 124 | else: 125 | sys.stderr.write(result['msg'] + '\n') 126 | sys.exit(1) 127 | -------------------------------------------------------------------------------- /examples/get_server_boot_once.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get the current System Boot Once target 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import json 25 | import redfish 26 | from redfish import redfish_logger 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def get_server_boot_once(ip, login_account, login_password, system_id): 32 | """Get server boot once item 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 40 | :type system_id: None or string 41 | :returns: returns server boot once item when succeeded or error message when failed 42 | """ 43 | result = {} 44 | login_host = "https://" + ip 45 | try: 46 | # Connect using the BMC address, account name, and password 47 | # Create a REDFISH object 48 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 49 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 50 | # Login into the server and create a session 51 | REDFISH_OBJ.login(auth=utils.g_AUTH) 52 | except: 53 | traceback.print_exc() 54 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 55 | return result 56 | 57 | # GET the ComputerSystem resource 58 | boot_details = [] 59 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 60 | if not system: 61 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 62 | REDFISH_OBJ.logout() 63 | return result 64 | for i in range(len(system)): 65 | system_url = system[i] 66 | response_system_url = REDFISH_OBJ.get(system_url, None) 67 | if response_system_url.status == 200: 68 | # Get the response 69 | boot_server = {} 70 | properties = ['BootSourceOverrideEnabled', 'BootSourceOverrideMode', 'BootSourceOverrideTarget'] 71 | for property in properties: 72 | if property in response_system_url.dict["Boot"]: 73 | boot_server[property] = response_system_url.dict["Boot"][property] 74 | boot_details.append(boot_server) 75 | else: 76 | result = {'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status} 77 | REDFISH_OBJ.logout() 78 | return result 79 | 80 | result['ret'] = True 81 | result['entries'] = boot_details 82 | # Logout of the current session 83 | try: 84 | REDFISH_OBJ.logout() 85 | except: 86 | pass 87 | return result 88 | 89 | 90 | if __name__ == '__main__': 91 | # Get parameters from config.ini and/or command line 92 | argget = utils.create_common_parameter_list() 93 | args = argget.parse_args() 94 | parameter_info = utils.parse_parameter(args) 95 | 96 | # Get connection info from the parameters user specified 97 | ip = parameter_info['ip'] 98 | login_account = parameter_info["user"] 99 | login_password = parameter_info["passwd"] 100 | system_id = parameter_info['sysid'] 101 | 102 | # Get server boot once item and check result 103 | result = get_server_boot_once(ip, login_account, login_password, system_id) 104 | if result['ret'] is True: 105 | del result['ret'] 106 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 107 | else: 108 | sys.stderr.write(result['msg'] + '\n') 109 | sys.exit(1) 110 | -------------------------------------------------------------------------------- /examples/get_server_boot_once_types.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get the current System Boot Once target 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import json 25 | import redfish 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | 30 | def get_server_boot_once_types(ip, login_account, login_password, system_id): 31 | """Get server boot once types 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :returns: returns server boot once types when succeeded or error message when failed 41 | """ 42 | result = {} 43 | login_host = "https://" + ip 44 | try: 45 | # Connect using the BMC address, account name, and password 46 | # Create a REDFISH object 47 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 48 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 49 | # Login into the server and create a session 50 | REDFISH_OBJ.login(auth=utils.g_AUTH) 51 | except: 52 | traceback.print_exc() 53 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 54 | return result 55 | # GET the ComputerSystem resource 56 | boot_details = [] 57 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 58 | if not system: 59 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 60 | REDFISH_OBJ.logout() 61 | return result 62 | for i in range(len(system)): 63 | system_url = system[i] 64 | response_system_url = REDFISH_OBJ.get(system_url, None) 65 | if response_system_url.status == 200: 66 | # Get the AllowableValues of the Boot.BootSourceOverrideTarget property 67 | boot_server = {} 68 | BootSourceOverrideTarget = response_system_url.dict["Boot"]["BootSourceOverrideTarget@Redfish.AllowableValues"] 69 | boot_server["BootSourceOverrideTarget@Redfish.AllowableValues"] = BootSourceOverrideTarget 70 | boot_details.append(boot_server) 71 | else: 72 | result = {'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status} 73 | REDFISH_OBJ.logout() 74 | return result 75 | 76 | result['ret'] = True 77 | result['entries'] = boot_details 78 | # Logout of the current session 79 | try: 80 | REDFISH_OBJ.logout() 81 | except: 82 | pass 83 | return result 84 | 85 | 86 | if __name__ == '__main__': 87 | # Get parameters from config.ini and/or command line 88 | argget = utils.create_common_parameter_list() 89 | args = argget.parse_args() 90 | parameter_info = utils.parse_parameter(args) 91 | 92 | # Get connection info from the parameters user specified 93 | ip = parameter_info['ip'] 94 | login_account = parameter_info["user"] 95 | login_password = parameter_info["passwd"] 96 | system_id = parameter_info['sysid'] 97 | 98 | # Get server boot once types and check result 99 | result = get_server_boot_once_types(ip, login_account, login_password, system_id) 100 | if result['ret'] is True: 101 | del result['ret'] 102 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 103 | else: 104 | sys.stderr.write(result['msg'] + '\n') 105 | sys.exit(1) 106 | -------------------------------------------------------------------------------- /examples/get_sessions.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get sessions information 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2019 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | def get_sessions(ip, login_account, login_password): 30 | """Get BMC inventory 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns session list when succeeded or error message when failed 38 | """ 39 | result = {} 40 | try: 41 | # Connect using the BMC address, account name, and password 42 | # Create a REDFISH object 43 | login_host = "https://" + ip 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 46 | # Login into the server and create a session 47 | REDFISH_OBJ.login(auth="basic") 48 | except: 49 | traceback.print_exc() 50 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 51 | return result 52 | 53 | session_list = [] 54 | # Get ServiceRoot resource 55 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 56 | # Get response_update_service_url 57 | if response_base_url.status == 200: 58 | session_service_url = response_base_url.dict['SessionService']['@odata.id'] 59 | else: 60 | result = {'ret': False, 'msg': "response base url Error code %s" % response_base_url.status} 61 | REDFISH_OBJ.logout() 62 | return result 63 | 64 | response_session_service_url = REDFISH_OBJ.get(session_service_url, None) 65 | if response_session_service_url.status == 200: 66 | sessions_url = response_session_service_url.dict['Sessions']['@odata.id'] 67 | response_sessions_url = REDFISH_OBJ.get(sessions_url, None) 68 | if response_sessions_url.status == 200: 69 | for single_session in response_sessions_url.dict["Members"]: 70 | single_session_url = single_session['@odata.id'] 71 | response_single_session = REDFISH_OBJ.get(single_session_url, None) 72 | if response_single_session.status == 200: 73 | session = {} 74 | for property in ['Name', 'UserName', 'Description', 'Id']: 75 | if property in response_single_session.dict: 76 | session[property] = response_single_session.dict[property] 77 | session_list.append(session) 78 | else: 79 | result = {'ret': False, 80 | 'msg': "response single session Error code %s" % response_single_session.status} 81 | REDFISH_OBJ.logout() 82 | return result 83 | else: 84 | result = {'ret': False, 'msg': "response sessions url Error code %s" % response_sessions_url.status} 85 | REDFISH_OBJ.logout() 86 | return result 87 | else: 88 | result = {'ret': False, 'msg': "response session service_url Error code %s" % response_session_service_url.status} 89 | REDFISH_OBJ.logout() 90 | return result 91 | 92 | result['ret'] = True 93 | result['sessions_details'] = session_list 94 | 95 | try: 96 | REDFISH_OBJ.logout() 97 | except: 98 | pass 99 | return result 100 | 101 | 102 | if __name__ == '__main__': 103 | # Get parameters from config.ini and/or command line 104 | argget = utils.create_common_parameter_list() 105 | args = argget.parse_args() 106 | parameter_info = utils.parse_parameter(args) 107 | 108 | # Get connection info from the parameters user specified 109 | ip = parameter_info['ip'] 110 | login_account = parameter_info["user"] 111 | login_password = parameter_info["passwd"] 112 | 113 | # Get sessions information and check result 114 | result = get_sessions(ip, login_account, login_password) 115 | 116 | if result['ret'] is True: 117 | del result['ret'] 118 | sys.stdout.write(json.dumps(result['sessions_details'], sort_keys=True, indent=2) + '\n') 119 | else: 120 | sys.stderr.write(result['msg'] + '\n') 121 | sys.exit(1) 122 | -------------------------------------------------------------------------------- /examples/get_system_reset_types.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get the current System Boot Once target 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import json 25 | import redfish 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | 30 | def get_system_reset_types(ip, login_account, login_password, system_id): 31 | """Get reset types 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :returns: returns reset types when succeeded or error message when failed 41 | """ 42 | result = {} 43 | login_host = "https://" + ip 44 | try: 45 | # Connect using the BMC address, account name, and password 46 | # Create a REDFISH object 47 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 48 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 49 | # Login into the server and create a session 50 | REDFISH_OBJ.login(auth=utils.g_AUTH) 51 | except: 52 | traceback.print_exc() 53 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct"} 54 | return result 55 | # GET the ComputerSystem resource 56 | reset_details = [] 57 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 58 | if not system: 59 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 60 | REDFISH_OBJ.logout() 61 | return result 62 | for i in range(len(system)): 63 | system_url = system[i] 64 | response_system_url = REDFISH_OBJ.get(system_url, None) 65 | if response_system_url.status == 200: 66 | # check whether Reset is supported 67 | if ("Actions" not in response_system_url.dict) or ("#ComputerSystem.Reset" not in response_system_url.dict["Actions"]): 68 | result = {'ret': False, 'msg': "Reset action is not supported."} 69 | REDFISH_OBJ.logout() 70 | return result 71 | 72 | # get AllowableValues for Reset action 73 | reset_types = {} 74 | if "ResetType@Redfish.AllowableValues" in response_system_url.dict["Actions"]["#ComputerSystem.Reset"]: 75 | Computer_reset = response_system_url.dict["Actions"]["#ComputerSystem.Reset"]["ResetType@Redfish.AllowableValues"] 76 | reset_types["ResetType@Redfish.AllowableValues"] = Computer_reset 77 | reset_details.append(reset_types) 78 | elif "@Redfish.ActionInfo" in response_system_url.dict["Actions"]["#ComputerSystem.Reset"]: 79 | actioninfo_url = response_system_url.dict["Actions"]["#ComputerSystem.Reset"]["@Redfish.ActionInfo"] 80 | response_actioninfo_url = REDFISH_OBJ.get(actioninfo_url, None) 81 | if response_actioninfo_url.status == 200: 82 | if "Parameters" in response_actioninfo_url.dict: 83 | for parameter in response_actioninfo_url.dict["Parameters"]: 84 | if ("Name" in parameter) and (parameter["Name"] == "ResetType"): 85 | if "AllowableValues" in parameter: 86 | reset_types["ResetType@Redfish.AllowableValues"] = parameter["AllowableValues"] 87 | reset_details.append(reset_types) 88 | else: 89 | result = {'ret': False, 'msg': "Get url %s failed. Error code %s" % (actioninfo_url, response_actioninfo_url.status)} 90 | REDFISH_OBJ.logout() 91 | return result 92 | if "ResetType@Redfish.AllowableValues" not in reset_types: 93 | result = {'ret': False, 'msg': "No AllowableValues information found for Reset action."} 94 | REDFISH_OBJ.logout() 95 | return result 96 | else: 97 | result = {'ret': False, 'msg': "response_system_url Error code %s" % response_system_url.status} 98 | REDFISH_OBJ.logout() 99 | return result 100 | 101 | result['ret'] = True 102 | result['entries'] = reset_details 103 | # Logout of the current session 104 | try: 105 | REDFISH_OBJ.logout() 106 | except: 107 | pass 108 | return result 109 | 110 | 111 | if __name__ == '__main__': 112 | # Get parameters from config.ini and/or command line 113 | argget = utils.create_common_parameter_list() 114 | args = argget.parse_args() 115 | parameter_info = utils.parse_parameter(args) 116 | 117 | # Get connection info from the parameters user specified 118 | ip = parameter_info['ip'] 119 | login_account = parameter_info["user"] 120 | login_password = parameter_info["passwd"] 121 | system_id = parameter_info['sysid'] 122 | 123 | # Get reset types and check result 124 | result = get_system_reset_types(ip, login_account, login_password, system_id) 125 | if result['ret'] is True: 126 | del result['ret'] 127 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 128 | else: 129 | sys.stderr.write(result['msg'] + '\n') 130 | sys.exit(1) 131 | 132 | -------------------------------------------------------------------------------- /examples/lenovo_callhome_getinfo.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get Call Home 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2023 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys, os 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def lenovo_callhome_getinfo(ip, login_account, login_password): 30 | """ Get Call Home 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns get call home result when succeeded or error message when failed 38 | """ 39 | 40 | result = {} 41 | 42 | # Create a REDFISH object 43 | login_host = "https://" + ip 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1') 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth="session") 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 53 | return result 54 | 55 | # Get /redfish/v1 56 | try: 57 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 58 | if response_base_url.status != 200: 59 | error_message = utils.get_extended_error(response_base_url) 60 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 61 | '/redfish/v1', response_base_url.status, error_message)} 62 | REDFISH_OBJ.logout() 63 | return result 64 | 65 | # Get /redfish/v1/Managers 66 | managers_url = response_base_url.dict['Managers']['@odata.id'] 67 | response_managers_url = REDFISH_OBJ.get(managers_url, None) 68 | if response_managers_url.status != 200: 69 | error_message = utils.get_extended_error(response_managers_url) 70 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 71 | managers_url, response_managers_url.status, error_message)} 72 | REDFISH_OBJ.logout() 73 | return result 74 | 75 | # Access /redfish/v1/Managers/1 to get ServiceAdvisor url 76 | advisor_url = None 77 | for request in response_managers_url.dict['Members']: 78 | request_url = request['@odata.id'] 79 | response_url = REDFISH_OBJ.get(request_url, None) 80 | if response_url.status != 200: 81 | error_message = utils.get_extended_error(response_url) 82 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 83 | request_url, response_url.status, error_message)} 84 | REDFISH_OBJ.logout() 85 | return result 86 | if 'ServiceAdvisor' in str(response_url.dict): 87 | advisor_url = response_url.dict['Oem']['Lenovo']['ServiceAdvisor'] 88 | break 89 | 90 | # Return here when ServiceAdvisor feature is not supported 91 | if advisor_url is None: 92 | result = {'ret': False, 'msg': 'ServiceAdvisor is not supported.'} 93 | REDFISH_OBJ.logout() 94 | return result 95 | 96 | # Access /redfish/v1/Managers/1/Oem/Lenovo/ServiceAdvisor 97 | response_url = REDFISH_OBJ.get(advisor_url, None) 98 | if response_url.status != 200: 99 | error_message = utils.get_extended_error(response_url) 100 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 101 | advisor_url, response_url.status, error_message)} 102 | REDFISH_OBJ.logout() 103 | return result 104 | callhome = {} 105 | if "AgreementAccepted" in response_url.dict: 106 | callhome['CallHomeSettings'] = response_url.dict['CallHomeSettings'] 107 | callhome['HTTPProxy'] = response_url.dict['HTTPProxy'] 108 | callhome['CallHomeEnabled'] = response_url.dict['CallHomeEnabled'] 109 | callhome['AgreementAccepted'] = response_url.dict['AgreementAccepted'] 110 | callhome['CountryCode'] = response_url.dict['CountryCode'] 111 | result['ret'] = True 112 | result['entries'] = callhome 113 | return result 114 | else: 115 | result = {'ret': False, 'msg': 'Call home is not supported.'} 116 | return result 117 | except Exception as e: 118 | traceback.print_exc() 119 | result = {'ret':False, 'msg':"Error message %s" %e} 120 | return result 121 | finally: 122 | try: 123 | REDFISH_OBJ.logout() 124 | except: 125 | pass 126 | 127 | def add_parameter(): 128 | """Add parameter""" 129 | argget = utils.create_common_parameter_list() 130 | args = argget.parse_args() 131 | parameter_info = utils.parse_parameter(args) 132 | return parameter_info 133 | 134 | if __name__ == '__main__': 135 | # Get parameters from config.ini and/or command line 136 | parameter_info = add_parameter() 137 | 138 | # Get connection info from the parameters user specified 139 | ip = parameter_info['ip'] 140 | login_account = parameter_info["user"] 141 | login_password = parameter_info["passwd"] 142 | 143 | result = lenovo_callhome_getinfo(ip, login_account, login_password) 144 | if result['ret'] is True: 145 | del result['ret'] 146 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 147 | else: 148 | sys.stderr.write(result['msg'] + '\n') 149 | sys.exit(1) 150 | 151 | 152 | -------------------------------------------------------------------------------- /examples/lenovo_del_alert_recipient.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - delete alert recipient specified (Email/Syslog Recipients) 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2020 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | def lenovo_del_alert_recipient(ip, login_account, login_password, index_id): 30 | """delete bmc alert recipient 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :params index_id: Id of alert recipient 38 | :type index_id: string 39 | :returns: returns the result to delete alert recipient or error message when failed 40 | """ 41 | result = {} 42 | # Connect using the BMC address, account name, and password 43 | # Create a REDFISH object 44 | login_host = "https://" + ip 45 | try: 46 | # Connect using the BMC address, account name, and password 47 | # Create a REDFISH object 48 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 49 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 50 | # Login into the server and create a session 51 | REDFISH_OBJ.login(auth=utils.g_AUTH) 52 | except Exception as e: 53 | traceback.print_exc() 54 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 55 | return result 56 | 57 | 58 | try: 59 | # Get ServiceBase resource 60 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 61 | 62 | # Get Managers collection resource 63 | managers_url = response_base_url.dict['Managers']['@odata.id'] 64 | response_managers_url = REDFISH_OBJ.get(managers_url, None) 65 | 66 | # Get Manager resource 67 | manager_url = response_managers_url.dict['Members'][0]['@odata.id'] 68 | response_manager_url = REDFISH_OBJ.get(manager_url, None) 69 | 70 | # Get bmc recipients url 71 | if 'Oem' in response_manager_url.dict and 'Lenovo' in response_manager_url.dict['Oem'] and 'Recipients' in response_manager_url.dict['Oem']['Lenovo']: 72 | recipients_url = response_manager_url.dict['Oem']['Lenovo']['Recipients']['@odata.id'] 73 | else: 74 | result = {'ret': False, 'msg': "No support to add alert recipient."} 75 | return result 76 | 77 | # Get alert recipients 78 | response_recipients_url = REDFISH_OBJ.get(recipients_url, None) 79 | if response_recipients_url.dict['Members@odata.count'] == 0: 80 | result = {'ret': False, 'msg': "No recipients exist."} 81 | return result 82 | 83 | # Find url of the recipient specified 84 | recipient_url = '' 85 | for member in response_recipients_url.dict['Members']: 86 | if index_id == member['@odata.id'].split("/")[-1]: 87 | recipient_url = member['@odata.id'] 88 | break 89 | 90 | if recipient_url == '': 91 | result = {'ret': False, 'msg': "The recipient specified does not exist."} 92 | return result 93 | 94 | headers = {"Content-Type": "application/json"} 95 | response_del_recipient = REDFISH_OBJ.delete(recipient_url, headers=headers) 96 | if response_del_recipient.status in [200, 204]: 97 | result = {"ret": True, "msg": "Delete alert recipient with Id %s successfully" % index_id} 98 | return result 99 | else: 100 | error_message = utils.get_extended_error(response_del_recipient) 101 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( \ 102 | recipient_url, response_del_recipient.status, error_message)} 103 | return result 104 | 105 | except Exception as e: 106 | traceback.print_exc() 107 | result = {'ret': False, 'msg': "Error message %s" %e} 108 | return result 109 | finally: 110 | # Logout of the current session 111 | try: 112 | REDFISH_OBJ.logout() 113 | except: 114 | pass 115 | 116 | 117 | def add_parameter(): 118 | """Add Id parameter to specify the alert recipient""" 119 | argget = utils.create_common_parameter_list(description_string="This tool can be used to get BMC alert recipients.") 120 | argget.add_argument('--Id', type=int, required=True, choices=range(1, 13), help='Id of the recipient, scope is 1 ~ 12. ') 121 | args = argget.parse_args() 122 | parameter_info = utils.parse_parameter(args) 123 | parameter_info["Id"] = str(args.Id) 124 | return parameter_info 125 | 126 | 127 | if __name__ == '__main__': 128 | # Get parameters from config.ini and/or command line 129 | parameter_info = add_parameter() 130 | 131 | # Get connection info from the parameters user specified 132 | ip = parameter_info['ip'] 133 | login_account = parameter_info["user"] 134 | login_password = parameter_info["passwd"] 135 | index_id = parameter_info["Id"] 136 | 137 | # Delete the alert recipient specified by Id and check result 138 | result = lenovo_del_alert_recipient(ip, login_account, login_password, index_id) 139 | if result['ret'] is True: 140 | del result['ret'] 141 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 142 | else: 143 | sys.stderr.write(result['msg'] + '\n') 144 | sys.exit(1) 145 | 146 | -------------------------------------------------------------------------------- /examples/lenovo_generate_snmp_engineid.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Generate Lenovo SNMP engine id 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | 24 | import sys 25 | import json 26 | import redfish 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def lenovo_generate_snmp_engineid(ip, login_account, login_password, system_id): 32 | """Generate SNMP engine id 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 40 | :type system_id: None or string 41 | :returns: returns generated SNMP engine id when succeeded or error message when failed 42 | """ 43 | result = {} 44 | login_host = "https://" + ip 45 | try: 46 | # Connect using the BMC address, account name, and password 47 | # Create a REDFISH object 48 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 49 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 50 | # Login into the server and create a session 51 | REDFISH_OBJ.login(auth=utils.g_AUTH) 52 | except Exception as e: 53 | traceback.print_exc() 54 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 55 | return result 56 | 57 | # GET the ComputerSystem resource 58 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 59 | if not system: 60 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 61 | REDFISH_OBJ.logout() 62 | return result 63 | 64 | sub_model = None 65 | serial_number = None 66 | host_name = None 67 | for i in range(len(system)): 68 | request_url = system[i] 69 | response_url = REDFISH_OBJ.get(request_url, None) 70 | if response_url.status != 200: 71 | error_message = utils.get_extended_error(response_url) 72 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 73 | request_url, response_url.status, error_message)} 74 | REDFISH_OBJ.logout() 75 | return result 76 | 77 | if 'SubModel' in response_url.dict: 78 | sub_model = response_url.dict['SubModel'] 79 | if 'SerialNumber' in response_url.dict: 80 | serial_number = response_url.dict['SerialNumber'] 81 | if 'HostName' in response_url.dict: 82 | host_name = response_url.dict['HostName'] 83 | 84 | engine_id_string = "" 85 | if sub_model is not None and serial_number is not None: 86 | engine_id_string = "XCC-%s-%s" %(sub_model, serial_number) 87 | elif host_name is not None: 88 | engine_id_string = "%s" %(host_name) 89 | else: 90 | result = {'ret': False, 'msg': "Failed to get necessary information from ComputeSystem for SNMP engine id generating."} 91 | REDFISH_OBJ.logout() 92 | return result 93 | 94 | engine_id_hexstr = "80 00 1F 88 04" 95 | for char in engine_id_string: 96 | engine_id_hexstr = engine_id_hexstr + ' %2X' %(ord(char)) 97 | result['ret'] = True 98 | result['data'] = engine_id_hexstr 99 | # Logout of the current session 100 | try: 101 | REDFISH_OBJ.logout() 102 | except: 103 | pass 104 | return result 105 | 106 | 107 | def add_parameter(): 108 | """Add parameter""" 109 | argget = utils.create_common_parameter_list() 110 | args = argget.parse_args() 111 | parameter_info = utils.parse_parameter(args) 112 | return parameter_info 113 | 114 | 115 | if __name__ == '__main__': 116 | # Get parameters from config.ini and/or command line 117 | parameter_info = add_parameter() 118 | 119 | # Get connection info from the parameters user specified 120 | ip = parameter_info['ip'] 121 | login_account = parameter_info["user"] 122 | login_password = parameter_info["passwd"] 123 | system_id = parameter_info['sysid'] 124 | 125 | # Call function to generate and check result 126 | result = lenovo_generate_snmp_engineid(ip, login_account, login_password, system_id) 127 | if result['ret'] is True: 128 | del result['ret'] 129 | sys.stdout.write(json.dumps(result['data'], sort_keys=True, indent=2) + '\n') 130 | else: 131 | sys.stderr.write(result['msg'] + '\n') 132 | sys.exit(1) 133 | 134 | -------------------------------------------------------------------------------- /examples/lenovo_get_alert_recipients.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - get alert recipients (Email/Syslog Recipients) 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2020 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | def lenovo_get_alert_recipients(ip, login_account, login_password): 30 | """get bmc alert recipients 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns bmc alert recipients or error message when failed 38 | """ 39 | result = {} 40 | # Connect using the BMC address, account name, and password 41 | # Create a REDFISH object 42 | login_host = "https://" + ip 43 | try: 44 | # Connect using the BMC address, account name, and password 45 | # Create a REDFISH object 46 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 47 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 48 | # Login into the server and create a session 49 | REDFISH_OBJ.login(auth=utils.g_AUTH) 50 | except Exception as e: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 53 | return result 54 | 55 | 56 | try: 57 | # Get ServiceBase resource 58 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 59 | 60 | # Get Managers collection resource 61 | managers_url = response_base_url.dict['Managers']['@odata.id'] 62 | response_managers_url = REDFISH_OBJ.get(managers_url, None) 63 | 64 | # Get Manager resource 65 | manager_url = response_managers_url.dict['Members'][0]['@odata.id'] 66 | response_manager_url = REDFISH_OBJ.get(manager_url, None) 67 | 68 | # Get bmc recipients url 69 | if 'Oem' in response_manager_url.dict and 'Lenovo' in response_manager_url.dict['Oem'] and 'Recipients' in response_manager_url.dict['Oem']['Lenovo']: 70 | recipients_url = response_manager_url.dict['Oem']['Lenovo']['Recipients']['@odata.id'] 71 | else: 72 | result = {'ret': False, 'msg': "No support to add alert recipient."} 73 | return result 74 | 75 | # Get alert recipients 76 | response_recipients_url = REDFISH_OBJ.get(recipients_url, None) 77 | if response_recipients_url.dict['Members@odata.count'] == 0: 78 | result = {'ret': True, 'msg': "No recipients exist.", 'entries':[]} 79 | return result 80 | 81 | all_recipients = [] 82 | items_excluded = ['@odata.type', '@odata.id', '@odata.etag'] 83 | for member in response_recipients_url.dict['Members']: 84 | recipient_url = member['@odata.id'] 85 | response_recipient_url = REDFISH_OBJ.get(recipient_url, None) 86 | if response_recipient_url.status not in [200, 201]: 87 | error_message = utils.get_extended_error(response_recipient_url) 88 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 89 | recipient_url, response_recipient_url.status, error_message)} 90 | return result 91 | recipient_dict = {} 92 | for key in response_recipient_url.dict: 93 | if key not in items_excluded: 94 | recipient_dict[key] = response_recipient_url.dict[key] 95 | all_recipients.append(recipient_dict) 96 | result = {"ret":True,"entries":all_recipients} 97 | return result 98 | 99 | except Exception as e: 100 | traceback.print_exc() 101 | result = {'ret':False, 'msg':"Error message %s" %e} 102 | return result 103 | finally: 104 | # Logout of the current session 105 | try: 106 | REDFISH_OBJ.logout() 107 | except: 108 | pass 109 | 110 | 111 | def add_parameter(): 112 | """Add common parameters""" 113 | argget = utils.create_common_parameter_list(description_string="This tool can be used to get BMC alert recipients.") 114 | args = argget.parse_args() 115 | parameter_info = utils.parse_parameter(args) 116 | return parameter_info 117 | 118 | 119 | if __name__ == '__main__': 120 | # Get parameters from config.ini and/or command line 121 | parameter_info = add_parameter() 122 | 123 | # Get connection info from the parameters user specified 124 | ip = parameter_info['ip'] 125 | login_account = parameter_info["user"] 126 | login_password = parameter_info["passwd"] 127 | 128 | # get alert recipients and check result 129 | result = lenovo_get_alert_recipients(ip, login_account, login_password) 130 | if result['ret'] is True: 131 | del result['ret'] 132 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 133 | else: 134 | sys.stderr.write(result['msg'] + '\n') 135 | sys.exit(1) 136 | 137 | -------------------------------------------------------------------------------- /examples/lenovo_get_bmc_user_global.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - get user global setting 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2019 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | def lenovo_get_bmc_user_global(ip, login_account, login_password): 30 | """get bmc user global settings 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns bmc user global setting or error message when failed 38 | """ 39 | result = {} 40 | # Connect using the BMC address, account name, and password 41 | # Create a REDFISH object 42 | login_host = "https://" + ip 43 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 44 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 45 | # Login into the server and create a session 46 | REDFISH_OBJ.login(auth=utils.g_AUTH) 47 | 48 | try: 49 | # Get response_base_url resource 50 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 51 | 52 | # Get account service url 53 | if response_base_url.status == 200: 54 | account_service_url = response_base_url.dict['AccountService']['@odata.id'] 55 | else: 56 | error_message = utils.get_extended_error(response_base_url) 57 | result = {'ret': False, 'msg': "Url '/redfish/v1' response Error code %s \nerror_message: %s" % ( 58 | response_base_url.status, error_message)} 59 | return result 60 | 61 | # Get AccountService resource 62 | response_account_service_url = REDFISH_OBJ.get(account_service_url, None) 63 | if response_account_service_url.status != 200: 64 | error_message = utils.get_extended_error(response_account_service_url) 65 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (account_service_url, response_account_service_url.status, error_message)} 66 | return result 67 | 68 | # Get global setting from AccoutService resource response 69 | global_setting = {} 70 | global_setting['AccountLockoutThreshold'] = response_account_service_url.dict['AccountLockoutThreshold'] 71 | global_setting['AccountLockoutDuration'] = response_account_service_url.dict['AccountLockoutDuration'] 72 | for item_name in ["PasswordChangeOnNextLogin", "AuthenticationMethod", 73 | "MinimumPasswordChangeIntervalHours", "PasswordExpirationPeriodDays", 74 | "PasswordChangeOnFirstAccess", "MinimumPasswordReuseCycle", 75 | "PasswordLength", "WebInactivitySessionTimeout", "PasswordExpirationWarningPeriod"]: 76 | if 'Oem' in response_account_service_url.dict and 'Lenovo' in response_account_service_url.dict['Oem']: 77 | if item_name in response_account_service_url.dict['Oem']['Lenovo']: 78 | global_setting[item_name] = response_account_service_url.dict['Oem']['Lenovo'][item_name] 79 | 80 | result['ret'] = True 81 | result['entries'] = global_setting 82 | 83 | except Exception as e: 84 | traceback.print_exc() 85 | result = {'ret':False, 'msg':"Error message %s" %e} 86 | finally: 87 | # Logout of the current session 88 | try: 89 | REDFISH_OBJ.logout() 90 | except: 91 | pass 92 | return result 93 | 94 | 95 | def add_parameter(): 96 | """Add update user password parameter""" 97 | argget = utils.create_common_parameter_list(description_string="This tool can be used to get BMC user global setting include password policy and web inactivity session timeout.") 98 | args = argget.parse_args() 99 | parameter_info = utils.parse_parameter(args) 100 | return parameter_info 101 | 102 | 103 | if __name__ == '__main__': 104 | # Get parameters from config.ini and/or command line 105 | parameter_info = add_parameter() 106 | 107 | # Get connection info from the parameters user specified 108 | ip = parameter_info['ip'] 109 | login_account = parameter_info["user"] 110 | login_password = parameter_info["passwd"] 111 | 112 | # Update user password result and check result 113 | result = lenovo_get_bmc_user_global(ip, login_account, login_password) 114 | if result['ret'] is True: 115 | del result['ret'] 116 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 117 | else: 118 | sys.stderr.write(result['msg'] + '\n') 119 | sys.exit(1) 120 | 121 | -------------------------------------------------------------------------------- /examples/lenovo_get_bmc_user_ldap_policy.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get BMC authentication method (local or ldap) 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | def lenovo_get_bmc_user_ldap_policy(ip, login_account, login_password): 29 | """get BMC authentication method 30 | :params ip: BMC IP address 31 | :type ip: string 32 | :params login_account: BMC user name 33 | :type login_account: string 34 | :params login_password: BMC user password 35 | :type login_password: string 36 | :returns: returns get BMC authentication method result when succeeded or error message when failed 37 | """ 38 | login_host = "https://" + ip 39 | 40 | # Connect using the BMC address, account name, and password 41 | # Create a REDFISH object 42 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 43 | password=login_password, default_prefix='/redfish/v1') 44 | 45 | # Login into the server and create a session 46 | try: 47 | REDFISH_OBJ.login(auth="session") 48 | except: 49 | traceback.print_exc() 50 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 51 | return result 52 | 53 | # Get ServiceBase resource 54 | try: 55 | # Get root service resource 56 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 57 | if response_base_url.status != 200: 58 | error_message = utils.get_extended_error(response_base_url) 59 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 60 | '/redfish/v1', response_base_url.status, error_message)} 61 | return result 62 | 63 | # Get AccountService resource 64 | accounts_url = response_base_url.dict['AccountService']['@odata.id'] 65 | response_accounts_url = REDFISH_OBJ.get(accounts_url, None) 66 | if response_accounts_url.status != 200: 67 | error_message = utils.get_extended_error(response_accounts_url) 68 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 69 | accounts_url, response_accounts_url.status, error_message)} 70 | return result 71 | 72 | # Use standard property LocalAccountAuth first 73 | logon_dict = {} 74 | if "LocalAccountAuth" in response_accounts_url.dict: 75 | value = response_accounts_url.dict["LocalAccountAuth"] 76 | mapdict = {"Enabled": "LocalOnly", "Disabled": "LDAPOnly", "Fallback": "LDAPFirstThenLocal", "LocalFirst": "LocalFirstThenLDAP"} 77 | if value in mapdict: 78 | logon_dict["AuthenticationMethod"] = mapdict[value] 79 | else: 80 | logon_dict["AuthenticationMethod"] = value 81 | result = {'ret': True, 'msg': logon_dict} 82 | return result 83 | 84 | # Use Oem property AuthenticationMethod instead if standard not existing 85 | if "Oem" in response_accounts_url.dict and response_accounts_url.dict["Oem"] and "Lenovo" in response_accounts_url.dict["Oem"]: 86 | if "AuthenticationMethod" in response_accounts_url.dict["Oem"]["Lenovo"]: 87 | logon_dict["AuthenticationMethod"] = response_accounts_url.dict["Oem"]["Lenovo"]["AuthenticationMethod"] 88 | result = {'ret': True, 'msg': logon_dict} 89 | return result 90 | 91 | # For ThinkSystem SR635/SR655 92 | if "Oem" in response_accounts_url.dict and response_accounts_url.dict["Oem"] and "Ami" in response_accounts_url.dict["Oem"]: 93 | result = {'ret': False, 'msg': 'Both local user and ldap can be supported. But policy setting is not supported.'} 94 | return result 95 | 96 | # No related resource found 97 | result = {'ret': False, 'msg': 'Only local user is supported'} 98 | return result 99 | 100 | except Exception as e: 101 | traceback.print_exc() 102 | result = {'ret': False, 'msg': 'exception msg %s' % e} 103 | return result 104 | finally: 105 | try: 106 | REDFISH_OBJ.logout() 107 | except: 108 | pass 109 | 110 | 111 | if __name__ == '__main__': 112 | # Get parameters from config.ini and/or command line 113 | argget = utils.create_common_parameter_list() 114 | args = argget.parse_args() 115 | parameter_info = utils.parse_parameter(args) 116 | 117 | # Get connection info from the parameters user specified 118 | ip = parameter_info['ip'] 119 | login_account = parameter_info["user"] 120 | login_password = parameter_info["passwd"] 121 | 122 | # Get logon mode and check result 123 | result = lenovo_get_bmc_user_ldap_policy(ip, login_account, login_password) 124 | if result['ret'] is True: 125 | del result['ret'] 126 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 127 | else: 128 | sys.stderr.write(result['msg'] + '\n') 129 | sys.exit(1) 130 | 131 | -------------------------------------------------------------------------------- /examples/lenovo_get_snmp_global.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get SNMP global information 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | 24 | import sys 25 | import json 26 | import redfish 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def lenovo_get_snmp_global(ip, login_account, login_password): 32 | """Get snmp global info 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :returns: returns snmp global information when succeeded or error message when failed 40 | """ 41 | result = {} 42 | login_host = "https://" + ip 43 | try: 44 | # Connect using the BMC address, account name, and password 45 | # Create a REDFISH object 46 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 47 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 48 | # Login into the server and create a session 49 | REDFISH_OBJ.login(auth=utils.g_AUTH) 50 | except Exception as e: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 53 | return result 54 | 55 | request_url = '/redfish/v1/Managers/1/NetworkProtocol/Oem/Lenovo/SNMP' 56 | 57 | response_url = REDFISH_OBJ.get(request_url, None) 58 | if response_url.status == 404: 59 | result = {'ret': False, 'msg': 'Target server does not support Oem SNMP resource.'} 60 | REDFISH_OBJ.logout() 61 | return result 62 | 63 | if response_url.status != 200: 64 | error_message = utils.get_extended_error(response_url) 65 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 66 | request_url, response_url.status, error_message)} 67 | REDFISH_OBJ.logout() 68 | return result 69 | 70 | snmpinfo = {} 71 | properties = ['SNMPv3Agent', 'SNMPTraps', 'CommunityNames'] 72 | for property in properties: 73 | if property in response_url.dict: 74 | snmpinfo[property] = response_url.dict[property] 75 | else: 76 | snmpinfo[property] = None 77 | 78 | result['ret'] = True 79 | result['snmpinfo'] = snmpinfo 80 | 81 | # Logout of the current session 82 | try: 83 | REDFISH_OBJ.logout() 84 | except: 85 | pass 86 | return result 87 | 88 | 89 | def add_parameter(): 90 | """Add parameter""" 91 | argget = utils.create_common_parameter_list() 92 | args = argget.parse_args() 93 | parameter_info = utils.parse_parameter(args) 94 | return parameter_info 95 | 96 | 97 | if __name__ == '__main__': 98 | # Get parameters from config.ini and/or command line 99 | parameter_info = add_parameter() 100 | 101 | # Get connection info from the parameters user specified 102 | ip = parameter_info['ip'] 103 | login_account = parameter_info["user"] 104 | login_password = parameter_info["passwd"] 105 | 106 | # Get snmp global info and check result 107 | result = lenovo_get_snmp_global(ip, login_account, login_password) 108 | if result['ret'] is True: 109 | del result['ret'] 110 | sys.stdout.write(json.dumps(result['snmpinfo'], sort_keys=True, indent=2) + '\n') 111 | else: 112 | sys.stderr.write(result['msg'] + '\n') 113 | sys.exit(1) 114 | 115 | -------------------------------------------------------------------------------- /examples/lenovo_httpfs_certificate_disable.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - disable security HTTPS to use certificate 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys, os 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def lenovo_httpfs_certificate_disable(ip, login_account, login_password): 30 | """ Disable HTTPS certificate 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns successful result when succeeded or error message when failed 38 | """ 39 | 40 | result = {} 41 | 42 | # Create a REDFISH object 43 | login_host = "https://" + ip 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1') 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth="session") 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 53 | return result 54 | 55 | try: 56 | # Get response_base_url 57 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 58 | if response_base_url.status != 200: 59 | error_message = utils.get_extended_error(response_base_url) 60 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ('/redfish/v1', response_base_url.status, error_message)} 61 | return result 62 | 63 | update_service_url = response_base_url.dict['UpdateService']['@odata.id'] 64 | response_update_service_url = REDFISH_OBJ.get(update_service_url, None) 65 | if response_update_service_url.status != 200: 66 | message = utils.get_extended_error(response_update_service_url) 67 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 68 | update_service_url, response_update_service_url.status, message)} 69 | return result 70 | if "VerifyRemoteServerCertificate" in response_update_service_url.dict: 71 | if response_update_service_url.dict["VerifyRemoteServerCertificate"] is False: 72 | result = {'ret': True, 'msg': "HTTPS certificate security is already disabled."} 73 | return result 74 | 75 | enable_body = {"VerifyRemoteServerCertificate": False} 76 | response_enable_verify = REDFISH_OBJ.patch(update_service_url, body=enable_body) 77 | if response_enable_verify.status == 200: 78 | result = {'ret': True, 'msg': "HTTPS certificate security is disabled."} 79 | return result 80 | else: 81 | message = utils.get_extended_error(response_enable_verify) 82 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 83 | update_service_url, response_enable_verify.status, message)} 84 | return result 85 | 86 | # No HTTPS certificate resource found 87 | result = {'ret': False, 'msg': "HTTPS certificate is not supported."} 88 | return result 89 | 90 | except Exception as e: 91 | traceback.print_exc() 92 | result = {'ret': False, 'msg': "error_message: %s" % (e)} 93 | finally: 94 | # Logout of the current session 95 | try: 96 | REDFISH_OBJ.logout() 97 | except: 98 | pass 99 | return result 100 | 101 | 102 | def add_parameter(): 103 | """Add parameter""" 104 | parameter_info = {} 105 | argget = utils.create_common_parameter_list() 106 | args = argget.parse_args() 107 | parameter_info = utils.parse_parameter(args) 108 | return parameter_info 109 | 110 | 111 | if __name__ == '__main__': 112 | # Get parameters from config.ini or command line 113 | parameter_info = add_parameter() 114 | ip = parameter_info['ip'] 115 | login_account = parameter_info["user"] 116 | login_password = parameter_info["passwd"] 117 | 118 | # Disable HTTPS certificate security and check result 119 | result = lenovo_httpfs_certificate_disable(ip, login_account, login_password) 120 | if result['ret'] is True: 121 | del result['ret'] 122 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 123 | else: 124 | sys.stderr.write(result['msg'] + '\n') 125 | sys.exit(1) 126 | -------------------------------------------------------------------------------- /examples/lenovo_httpfs_certificate_enable.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - enable security HTTPS to use certificate 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys, os 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def lenovo_httpfs_certificate_enable(ip, login_account, login_password): 30 | """ Enable HTTPS certificate 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns successful result when succeeded or error message when failed 38 | """ 39 | 40 | result = {} 41 | 42 | # Create a REDFISH object 43 | login_host = "https://" + ip 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1') 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth="session") 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 53 | return result 54 | 55 | try: 56 | # Get response_base_url 57 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 58 | if response_base_url.status != 200: 59 | error_message = utils.get_extended_error(response_base_url) 60 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ('/redfish/v1', response_base_url.status, error_message)} 61 | return result 62 | 63 | update_service_url = response_base_url.dict['UpdateService']['@odata.id'] 64 | response_update_service_url = REDFISH_OBJ.get(update_service_url, None) 65 | if response_update_service_url.status != 200: 66 | message = utils.get_extended_error(response_update_service_url) 67 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 68 | update_service_url, response_update_service_url.status, message)} 69 | return result 70 | if "VerifyRemoteServerCertificate" in response_update_service_url.dict: 71 | if response_update_service_url.dict["VerifyRemoteServerCertificate"] is True: 72 | result = {'ret': True, 'msg': "HTTPS certificate security is already enabled."} 73 | return result 74 | 75 | enable_body = {"VerifyRemoteServerCertificate": True} 76 | response_enable_verify = REDFISH_OBJ.patch(update_service_url, body=enable_body) 77 | if response_enable_verify.status == 200: 78 | result = {'ret': True, 'msg': "HTTPS certificate security is enabled." 79 | "Note that in order to enable SSL, a valid SSL certificate must first be in place and at least one SSL client trusted certificate must be imported."} 80 | return result 81 | else: 82 | message = utils.get_extended_error(response_enable_verify) 83 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 84 | update_service_url, response_enable_verify.status, message)} 85 | return result 86 | 87 | # No HTTPS certificate resource found 88 | result = {'ret': False, 'msg': "HTTPS certificate is not supported."} 89 | return result 90 | 91 | except Exception as e: 92 | traceback.print_exc() 93 | result = {'ret': False, 'msg': "error_message: %s" % (e)} 94 | finally: 95 | # Logout of the current session 96 | try: 97 | REDFISH_OBJ.logout() 98 | except: 99 | pass 100 | return result 101 | 102 | 103 | def add_parameter(): 104 | """Add parameter""" 105 | parameter_info = {} 106 | argget = utils.create_common_parameter_list() 107 | args = argget.parse_args() 108 | parameter_info = utils.parse_parameter(args) 109 | return parameter_info 110 | 111 | 112 | if __name__ == '__main__': 113 | # Get parameters from config.ini or command line 114 | parameter_info = add_parameter() 115 | ip = parameter_info['ip'] 116 | login_account = parameter_info["user"] 117 | login_password = parameter_info["passwd"] 118 | 119 | # Enable HTTPS certificate security and check result 120 | result = lenovo_httpfs_certificate_enable(ip, login_account, login_password) 121 | if result['ret'] is True: 122 | del result['ret'] 123 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 124 | else: 125 | sys.stderr.write(result['msg'] + '\n') 126 | sys.exit(1) 127 | -------------------------------------------------------------------------------- /examples/lenovo_httpfs_certificate_getinfo.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get HTTPS certificate info 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | import sys, os 23 | import redfish 24 | import json 25 | import traceback 26 | import lenovo_utils as utils 27 | 28 | 29 | def lenovo_httpfs_certificate_getinfo(ip, login_account, login_password): 30 | """ Get HTTPS certificate info 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :returns: returns successful result when succeeded or error message when failed 38 | """ 39 | 40 | result = {} 41 | 42 | # Create a REDFISH object 43 | login_host = "https://" + ip 44 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 45 | password=login_password, default_prefix='/redfish/v1') 46 | 47 | # Login into the server and create a session 48 | try: 49 | REDFISH_OBJ.login(auth="session") 50 | except: 51 | traceback.print_exc() 52 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 53 | return result 54 | 55 | try: 56 | # Get response_base_url 57 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 58 | if response_base_url.status != 200: 59 | error_message = utils.get_extended_error(response_base_url) 60 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ('/redfish/v1', response_base_url.status, error_message)} 61 | return result 62 | 63 | update_service_url = response_base_url.dict['UpdateService']['@odata.id'] 64 | response_update_service_url = REDFISH_OBJ.get(update_service_url, None) 65 | if response_update_service_url.status != 200: 66 | message = utils.get_extended_error(response_update_service_url) 67 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 68 | update_service_url, response_update_service_url.status, message)} 69 | return result 70 | # Check /redfish/v1/UpdateService/RemoteServerCertificates existing 71 | if "RemoteServerCertificates" in response_update_service_url.dict: 72 | remote_cert_url = response_update_service_url.dict["RemoteServerCertificates"]["@odata.id"] 73 | response_remote_cert = REDFISH_OBJ.get(remote_cert_url, None) 74 | if response_remote_cert.status != 200: 75 | message = utils.get_extended_error(response_remote_cert) 76 | result = {'ret': False, 'msg': "Url '%s' response Error code %s, \nError message :%s" % ( 77 | remote_cert_url, response_remote_cert.status, message)} 78 | return result 79 | if "Members" in response_remote_cert.dict: 80 | all_certs = [] 81 | for member in response_remote_cert.dict["Members"]: 82 | request_get_url = member["@odata.id"] 83 | response_get_url = REDFISH_OBJ.get(request_get_url, None) 84 | if response_get_url.status == 200: 85 | cert_info = {} 86 | for property in ['ValidNotAfter', 'ValidNotBefore', 'KeyUsage', 'CertificateType', 87 | 'Subject', 'CertificateString', 'Issuer', 'Id', '@odata.id']: 88 | if property in response_get_url.dict: 89 | cert_info[property] = response_get_url.dict[property] 90 | all_certs.append(cert_info) 91 | else: 92 | message = utils.get_extended_error(response_get_url) 93 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 94 | request_get_url, response_get_url.status, message)} 95 | return result 96 | 97 | result = {'ret': True, 'entries': all_certs} 98 | return result 99 | 100 | # No HTTPS certificate resource found 101 | result = {'ret': False, 'msg': "HTTPS certificate is not supported."} 102 | return result 103 | 104 | except Exception as e: 105 | traceback.print_exc() 106 | result = {'ret': False, 'msg': "error_message: %s" % (e)} 107 | finally: 108 | # Logout of the current session 109 | try: 110 | REDFISH_OBJ.logout() 111 | except: 112 | pass 113 | return result 114 | 115 | 116 | def add_parameter(): 117 | """Add parameter""" 118 | parameter_info = {} 119 | argget = utils.create_common_parameter_list() 120 | args = argget.parse_args() 121 | parameter_info = utils.parse_parameter(args) 122 | return parameter_info 123 | 124 | 125 | if __name__ == '__main__': 126 | # Get parameters from config.ini or command line 127 | parameter_info = add_parameter() 128 | ip = parameter_info['ip'] 129 | login_account = parameter_info["user"] 130 | login_password = parameter_info["passwd"] 131 | 132 | # Get HTTPS certificate info and check result 133 | result = lenovo_httpfs_certificate_getinfo(ip, login_account, login_password) 134 | if result['ret'] is True: 135 | del result['ret'] 136 | sys.stdout.write(json.dumps(result['entries'], sort_keys=True, indent=2) + '\n') 137 | else: 138 | sys.stderr.write(result['msg'] + '\n') 139 | sys.exit(1) 140 | -------------------------------------------------------------------------------- /examples/raw_command_get.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Get the resource information from specified uri 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | 24 | import sys 25 | import json 26 | import redfish 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def raw_command_get(ip, login_account, login_password, resource_uri): 32 | """Get specified resource information 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :params resource_uri: redfish resource uri 40 | :type resource_uri: string 41 | :returns: returns specified resource information when succeeded or error message when failed 42 | """ 43 | result = {} 44 | login_host = "https://" + ip 45 | try: 46 | # Connect using the BMC address, account name, and password 47 | # Create a REDFISH object 48 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 49 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 50 | # Login into the server and create a session 51 | REDFISH_OBJ.login(auth=utils.g_AUTH) 52 | except Exception as e: 53 | traceback.print_exc() 54 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 55 | return result 56 | 57 | request_url = resource_uri 58 | 59 | response_url = REDFISH_OBJ.get(request_url, None) 60 | if response_url.status != 200: 61 | error_message = utils.get_extended_error(response_url) 62 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 63 | request_url, response_url.status, error_message)} 64 | REDFISH_OBJ.logout() 65 | return result 66 | 67 | resource_details = response_url.dict 68 | 69 | result['ret'] = True 70 | result['data'] = resource_details 71 | # Logout of the current session 72 | try: 73 | REDFISH_OBJ.logout() 74 | except: 75 | pass 76 | return result 77 | 78 | 79 | def add_helpmessage(parser): 80 | parser.add_argument('--resource_uri', type=str, required=True, 81 | help='Specify redfish resource uri. Ex: "/redfish/v1/Systems/1"') 82 | 83 | 84 | def add_parameter(): 85 | """Add parameter""" 86 | argget = utils.create_common_parameter_list() 87 | add_helpmessage(argget) 88 | args = argget.parse_args() 89 | parameter_info = utils.parse_parameter(args) 90 | parameter_info["resource_uri"] = args.resource_uri 91 | return parameter_info 92 | 93 | 94 | if __name__ == '__main__': 95 | # Get parameters from config.ini and/or command line 96 | parameter_info = add_parameter() 97 | 98 | # Get connection info from the parameters user specified 99 | ip = parameter_info['ip'] 100 | login_account = parameter_info["user"] 101 | login_password = parameter_info["passwd"] 102 | 103 | # Get resource_uri 104 | resource_uri = parameter_info["resource_uri"] 105 | 106 | # Get resource information and check result 107 | result = raw_command_get(ip, login_account, login_password, resource_uri) 108 | if result['ret'] is True: 109 | del result['ret'] 110 | sys.stdout.write(json.dumps(result['data'], sort_keys=True, indent=2) + '\n') 111 | else: 112 | sys.stderr.write(result['msg'] + '\n') 113 | sys.exit(1) 114 | 115 | -------------------------------------------------------------------------------- /examples/raw_command_patch.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Patch specified uri with specified body 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2021 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | 24 | import sys 25 | import json 26 | import redfish 27 | import traceback 28 | import lenovo_utils as utils 29 | 30 | 31 | def raw_command_patch(ip, login_account, login_password, resource_uri, body): 32 | """Patch specified resource 33 | :params ip: BMC IP address 34 | :type ip: string 35 | :params login_account: BMC user name 36 | :type login_account: string 37 | :params login_password: BMC user password 38 | :type login_password: string 39 | :params resource_uri: redfish resource uri 40 | :type resource_uri: string 41 | :params body: json string body for redfish patch request 42 | :type body: string 43 | :returns: returns specified resource information when succeeded or error message when failed 44 | """ 45 | result = {} 46 | login_host = "https://" + ip 47 | try: 48 | # Connect using the BMC address, account name, and password 49 | # Create a REDFISH object 50 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 51 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE, max_retry=3) 52 | # Login into the server and create a session 53 | REDFISH_OBJ.login(auth=utils.g_AUTH) 54 | except Exception as e: 55 | traceback.print_exc() 56 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 57 | return result 58 | 59 | request_url = resource_uri 60 | 61 | headers = {"If-Match": "*"} 62 | response_url = REDFISH_OBJ.patch(request_url, body=json.loads(body), headers=headers) 63 | if response_url.status not in [200, 204]: 64 | error_message = utils.get_extended_error(response_url) 65 | result = {'ret': False, 'msg': "Url '%s' response Error code %s\nerror_message: %s" % ( 66 | request_url, response_url.status, error_message)} 67 | REDFISH_OBJ.logout() 68 | return result 69 | 70 | message_extendedinfo = "" 71 | if response_url.status == 200 and "@Message.ExtendedInfo" in response_url.dict: 72 | message_extendedinfo = "@Message.ExtendedInfo: " + str(response_url.dict["@Message.ExtendedInfo"]) 73 | 74 | result['ret'] = True 75 | result['msg'] = "Update resource uri %s successfully. %s" %(resource_uri, message_extendedinfo) 76 | # Logout of the current session 77 | try: 78 | REDFISH_OBJ.logout() 79 | except: 80 | pass 81 | return result 82 | 83 | 84 | def add_helpmessage(parser): 85 | parser.add_argument('--resource_uri', type=str, required=True, 86 | help='Specify redfish resource uri. Ex: "/redfish/v1/Systems/1"') 87 | parser.add_argument('--body', type=str, required=True, 88 | help='Specify json string body for redfish patch request. Ex: "{\\"AssetTag\\": \\"new_asset_tag\\"}"') 89 | 90 | 91 | def add_parameter(): 92 | """Add parameter""" 93 | argget = utils.create_common_parameter_list() 94 | add_helpmessage(argget) 95 | args = argget.parse_args() 96 | parameter_info = utils.parse_parameter(args) 97 | parameter_info["resource_uri"] = args.resource_uri 98 | parameter_info["body"] = args.body 99 | return parameter_info 100 | 101 | 102 | if __name__ == '__main__': 103 | # Get parameters from config.ini and/or command line 104 | parameter_info = add_parameter() 105 | 106 | # Get connection info from the parameters user specified 107 | ip = parameter_info['ip'] 108 | login_account = parameter_info["user"] 109 | login_password = parameter_info["passwd"] 110 | 111 | # Get resource_uri and body 112 | resource_uri = parameter_info["resource_uri"] 113 | body = parameter_info["body"] 114 | 115 | # Patch redfish resource with body and check result 116 | result = raw_command_patch(ip, login_account, login_password, resource_uri, body) 117 | if result['ret'] is True: 118 | del result['ret'] 119 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 120 | else: 121 | sys.stderr.write(result['msg'] + '\n') 122 | sys.exit(1) 123 | 124 | -------------------------------------------------------------------------------- /examples/set_bmc_timezone.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Set BMC timezone 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2020 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import lenovo_utils as utils 27 | 28 | 29 | def set_bmc_timezone(ip, login_account, login_password, timezone): 30 | """Set BMC timezone 31 | :params ip: BMC IP address 32 | :type ip: string 33 | :params login_account: BMC user name 34 | :type login_account: string 35 | :params login_password: BMC user password 36 | :type login_password: string 37 | :params timezone: timezone by user specified 38 | :type timezone: string 39 | :returns: returns set BMC timezone result when succeeded or error message when failed 40 | """ 41 | result = {} 42 | login_host = "https://" + ip 43 | 44 | # Connect using the BMC address, account name, and password 45 | # Create a REDFISH object 46 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 47 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 48 | 49 | # Login into the server and create a session 50 | REDFISH_OBJ.login(auth=utils.g_AUTH) 51 | 52 | # Get ServiceBase resource 53 | response_base_url = REDFISH_OBJ.get('/redfish/v1', None) 54 | # Get response_base_url 55 | if response_base_url.status == 200: 56 | manager_url = response_base_url.dict['Managers']['@odata.id'] 57 | else: 58 | error_message = utils.get_extended_error(response_base_url) 59 | result = {'ret': False, 'msg': "Url '/redfish/v1' response error code %s \nerror_message: %s" % ( 60 | response_base_url.status, error_message)} 61 | REDFISH_OBJ.logout() 62 | return result 63 | 64 | # Get the manager url response resource 65 | response_manager_url = REDFISH_OBJ.get(manager_url, None) 66 | if response_manager_url.status != 200: 67 | error_message = utils.get_extended_error(response_manager_url) 68 | result = {'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % ( 69 | manager_url, response_manager_url.status, error_message)} 70 | REDFISH_OBJ.logout() 71 | return result 72 | for request in response_manager_url.dict['Members']: 73 | request_url = request['@odata.id'] 74 | response_url = REDFISH_OBJ.get(request_url, None) 75 | if response_url.status != 200: 76 | error_message = utils.get_extended_error(response_url) 77 | result = {'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % ( 78 | request_url, response_url.status, error_message)} 79 | REDFISH_OBJ.logout() 80 | return result 81 | 82 | # get etag to set If-Match precondition 83 | if "@odata.etag" in response_url.dict: 84 | etag = response_url.dict['@odata.etag'] 85 | else: 86 | etag = "*" 87 | headers = {"If-Match": etag} 88 | 89 | # Build patch body for request to set timezone 90 | payload = {"DateTimeLocalOffset":timezone} 91 | response_url = REDFISH_OBJ.patch(request_url, body=payload, headers=headers) 92 | if response_url.status in [200,204]: 93 | result = {'ret': True, 'msg': "Set BMC timezone successfully"} 94 | try: 95 | REDFISH_OBJ.logout() 96 | except: 97 | pass 98 | return result 99 | else: 100 | error_message = utils.get_extended_error(response_url) 101 | result = {'ret': False, 'msg': "Url '%s' response error code %s \nerror_message: %s" % ( 102 | request_url, response_url.status, error_message)} 103 | REDFISH_OBJ.logout() 104 | return result 105 | 106 | 107 | def add_helpmessage(argget): 108 | argget.add_argument('--timezone', type=str, required=True, help="Specify the time offset from UTC, format should be +HH:MM or -HH:MM, such as '+08:00', ' -05:00'. For current timezone, you can call get_bmc_inventory script and check DateTimeLocalOffset property") 109 | 110 | 111 | def add_parameter(): 112 | """Add set BMC timezone parameter""" 113 | argget = utils.create_common_parameter_list() 114 | add_helpmessage(argget) 115 | args = argget.parse_args() 116 | parameter_info = utils.parse_parameter(args) 117 | parameter_info["timezone"] = args.timezone 118 | return parameter_info 119 | 120 | 121 | if __name__ == '__main__': 122 | # Get parameters from config.ini and/or command line 123 | parameter_info = add_parameter() 124 | 125 | # Get connection info from the parameters user specified 126 | ip = parameter_info['ip'] 127 | login_account = parameter_info["user"] 128 | login_password = parameter_info["passwd"] 129 | timezone = parameter_info['timezone'].strip() 130 | 131 | # Set BMC timezone result and check result 132 | result = set_bmc_timezone(ip, login_account, login_password, timezone) 133 | if result['ret'] is True: 134 | del result['ret'] 135 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 136 | else: 137 | sys.stderr.write(result['msg'] + '\n') 138 | sys.exit(1) 139 | -------------------------------------------------------------------------------- /examples/set_power_state.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Reset System with the selected Reset Type 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import json 25 | import redfish 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | 30 | def set_power_state(ip, login_account, login_password, system_id, reset_type): 31 | """Reset system 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :params reset_type: reset system type by user specified 41 | :type reset_type: string 42 | :returns: returns reset system type result when succeeded or error message when failed 43 | """ 44 | result = {} 45 | login_host = "https://" + ip 46 | try: 47 | # Connect using the address, account name, and password 48 | # Create a REDFISH object 49 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 50 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 51 | # Login into the server and create a session 52 | REDFISH_OBJ.login(auth=utils.g_AUTH) 53 | except Exception as e: 54 | traceback.print_exc() 55 | result = {'ret': False, 'msg': "Error_message: %s. Please check if username, password and IP are correct" % repr(e)} 56 | return result 57 | 58 | try: 59 | # GET the ComputerSystem resource 60 | system = utils.get_system_url("/redfish/v1", system_id, REDFISH_OBJ) 61 | if not system: 62 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 63 | REDFISH_OBJ.logout() 64 | return result 65 | for i in range(len(system)): 66 | system_url = system[i] 67 | # GET the ComputerSystem resource 68 | response_system_url = REDFISH_OBJ.get(system_url, None) 69 | if response_system_url.status == 200: 70 | # Find the Reset Action target URL 71 | target_url = response_system_url.dict["Actions"]["#ComputerSystem.Reset"]["target"] 72 | # Prepare POST body 73 | post_body = {"ResetType": reset_type} 74 | # POST Reset Action 75 | post_response = REDFISH_OBJ.post(target_url, body=post_body) 76 | # If Response return 200/OK, return successful , else print the response Error code 77 | if post_response.status in [200, 202, 204]: 78 | result = {'ret': True, 'msg': "reset system '%s' successful" % reset_type} 79 | else: 80 | error_message = utils.get_extended_error(post_response) 81 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 82 | target_url, post_response.status, error_message)} 83 | return result 84 | else: 85 | error_message = utils.get_extended_error(response_system_url) 86 | result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % ( 87 | system_url, response_system_url.status, error_message)} 88 | return result 89 | 90 | except Exception as e: 91 | traceback.print_exc() 92 | result = {'ret': False, 'msg': "error_message: %s" % e} 93 | finally: 94 | # Logout of the current session 95 | try: 96 | REDFISH_OBJ.logout() 97 | except: 98 | pass 99 | return result 100 | 101 | 102 | def add_helpmessage(argget): 103 | argget.add_argument('--resettype', type=str, required=True, help='Input the reset system type("On", "Nmi", "GracefulShutdown", "GracefulRestart", "ForceOn", "ForceOff", "ForceRestart")') 104 | 105 | 106 | def add_parameter(): 107 | """Add reset system parameter""" 108 | argget = utils.create_common_parameter_list() 109 | add_helpmessage(argget) 110 | args = argget.parse_args() 111 | parameter_info = utils.parse_parameter(args) 112 | parameter_info['reset_type'] = args.resettype 113 | return parameter_info 114 | 115 | 116 | if __name__ == '__main__': 117 | # Get parameters from config.ini and/or command line 118 | parameter_info = add_parameter() 119 | 120 | # Get connection info from the parameters user specified 121 | ip = parameter_info['ip'] 122 | login_account = parameter_info["user"] 123 | login_password = parameter_info["passwd"] 124 | system_id = parameter_info['sysid'] 125 | 126 | # Get set info from the parameters user specified 127 | try: 128 | reset_type = parameter_info['reset_type'] 129 | except: 130 | sys.stderr.write("Please run the command 'python %s -h' to view the help info" % sys.argv[0]) 131 | sys.exit(1) 132 | 133 | # Reset system result and check result 134 | result = set_power_state(ip, login_account, login_password,system_id, reset_type) 135 | if result['ret'] is True: 136 | del result['ret'] 137 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 138 | else: 139 | sys.stderr.write(result['msg'] + '\n') 140 | sys.exit(1) 141 | -------------------------------------------------------------------------------- /examples/set_server_asset_tag.py: -------------------------------------------------------------------------------- 1 | ### 2 | # 3 | # Lenovo Redfish examples - Set server asset tag 4 | # 5 | # Copyright Notice: 6 | # 7 | # Copyright 2018 Lenovo Corporation 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | # not use this file except in compliance with the License. You may obtain 11 | # a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 18 | # License for the specific language governing permissions and limitations 19 | # under the License. 20 | ### 21 | 22 | 23 | import sys 24 | import redfish 25 | import json 26 | import traceback 27 | import lenovo_utils as utils 28 | 29 | 30 | def set_server_asset_tag(ip, login_account, login_password, system_id, asset_tag): 31 | """Set server asset tag 32 | :params ip: BMC IP address 33 | :type ip: string 34 | :params login_account: BMC user name 35 | :type login_account: string 36 | :params login_password: BMC user password 37 | :type login_password: string 38 | :params system_id: ComputerSystem instance id(None: first instance, All: all instances) 39 | :type system_id: None or string 40 | :params asset_tag: asset tag by user specified 41 | :type asset_tag: string 42 | :returns: returns set server asset tag result when succeeded or error message when failed 43 | """ 44 | result = {} 45 | try: 46 | # Connect using the BMC address, account name, and password 47 | # Create a REDFISH object 48 | login_host = "https://" + ip 49 | REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, 50 | password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE) 51 | # Login into the server and create a session 52 | REDFISH_OBJ.login(auth=utils.g_AUTH) 53 | except: 54 | traceback.print_exc() 55 | result = {'ret': False, 'msg': "Please check the username, password, IP is correct\n"} 56 | return result 57 | try: 58 | # GET the ComputerSystem resource 59 | system = utils.get_system_url("/redfish/v1",system_id, REDFISH_OBJ) 60 | if not system: 61 | result = {'ret': False, 'msg': "This system id is not exist or system member is None"} 62 | return result 63 | 64 | for i in range(len(system)): 65 | system_url = system[i] 66 | # get etag to set If-Match precondition 67 | response_system_url = REDFISH_OBJ.get(system_url, None) 68 | if response_system_url.status != 200: 69 | error_message = utils.get_extended_error(response_system_url) 70 | result = {'ret': False, 'msg': "Url '%s' get failed. response Error code %s \nerror_message: %s" % ( 71 | system_url, response_system_url.status, error_message)} 72 | return result 73 | if "@odata.etag" in response_system_url.dict: 74 | etag = response_system_url.dict['@odata.etag'] 75 | else: 76 | etag = "" 77 | headers = {"If-Match": etag} 78 | 79 | # perform patch to set assettag 80 | parameter = {"AssetTag": asset_tag} 81 | response_asset_tag = REDFISH_OBJ.patch(system_url, body=parameter, headers=headers) 82 | if response_asset_tag.status in [200, 204]: 83 | result = {'ret': True, 84 | 'msg': "PATCH command successfully completed for set server asset tag to %s" % asset_tag} 85 | else: 86 | error_message = utils.get_extended_error(response_asset_tag) 87 | result = {'ret': False, 'msg': "Url '%s' patch failed. response Error code %s \nerror_message: %s" % ( 88 | system_url, response_asset_tag.status, error_message)} 89 | except Exception as e: 90 | traceback.print_exc() 91 | result = {'ret': False, 'msg': "error_message: %s" % e} 92 | finally: 93 | # Logout of the current session 94 | try: 95 | REDFISH_OBJ.logout() 96 | except: 97 | pass 98 | return result 99 | 100 | 101 | import argparse 102 | def add_helpmessage(parser): 103 | parser.add_argument('--assettag', type=str, required=True, help='Input the assettag info(Maximum string length of AssetTag is 32)') 104 | 105 | 106 | def add_parameter(): 107 | """Add set server asset tag parameter""" 108 | argget = utils.create_common_parameter_list() 109 | add_helpmessage(argget) 110 | args = argget.parse_args() 111 | parameter_info = utils.parse_parameter(args) 112 | parameter_info['asset_tag'] = args.assettag 113 | return parameter_info 114 | 115 | 116 | if __name__ == '__main__': 117 | # Get parameters from config.ini and/or command line 118 | parameter_info = add_parameter() 119 | 120 | # Get connection info from the parameters user specified 121 | ip = parameter_info['ip'] 122 | login_account = parameter_info["user"] 123 | login_password = parameter_info["passwd"] 124 | system_id = parameter_info['sysid'] 125 | 126 | # Get set info from the parameters user specified 127 | try: 128 | asset_tag = parameter_info['asset_tag'] 129 | except: 130 | sys.stderr.write("Please run the command 'python %s -h' to view the help info" % sys.argv[0]) 131 | sys.exit(1) 132 | 133 | # Set server asset tag result and check result 134 | result = set_server_asset_tag(ip, login_account, login_password, system_id, asset_tag) 135 | if result['ret'] is True: 136 | del result['ret'] 137 | sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2) + '\n') 138 | else: 139 | sys.stderr.write(result['msg'] + '\n') 140 | sys.exit(1) 141 | --------------------------------------------------------------------------------