iDRAC Redfish API Automation: Python and PowerShell Patterns - 夜莺博客

iDRAC Redfish API Automation: Python and PowerShell Patterns

Every fleet has a script that logs into iDRACs over SSH and scrapes racadm output. Redfish replaces that with a documented HTTPS API that returns JSON, works the same way on iDRAC7 through iDRAC10, and encrypts everything in transit by default. This article covers the authentication model, the handful of endpoints that do most of the work, Python and PowerShell patterns, and the workflows Dell ships as reference scripts so you do not have to write them from scratch.

Why Redfish Beats SSH and racadm Scripting

SSH plus racadm works, but it is fragile in exactly the ways that hurt at scale. The output is text that changes format between firmware versions, so every parser breaks on upgrade. Credentials pass over a session that many shops leave with the default self-signed key handling. There is no consistent way to ask "give me all firmware versions as structured data" - you get a wall of console text you have to parse.

Redfish is a DMTF standard that Dell, HPE, Lenovo, Supermicro and others implement. It exposes the same resources with the same JSON shape across vendors and generations, so a script written against iDRAC9 mostly works untouched on iDRAC10 and translates directly to iLO or XCC with different base URLs. That portability, plus first-class TLS and a real session model, is why it is the right default for new automation.

Authentication: session token, not credentials per call

POST credentials once to create a session, then use the returned X-Auth-Token (and the session URI) for every subsequent call. That avoids re-authenticating on every request and keeps credentials out of your process list.

# Create a session
curl -sk -X POST "https://10.0.0.10/redfish/v1/SessionService/Sessions" \
  -H "Content-Type: application/json" \
  -d '{"UserName":"root","Password":"calvin"}' -D headers.txt

# Reuse the token for everything else
TOKEN=$(grep -i x-auth-token headers.txt | awk '{print $2}')
curl -sk -H "X-Auth-Token: *** "https://10.0.0.10/redfish/v1/Systems/System.Embedded.1" | jq .

Use -k only in the lab. In production, trust the iDRAC certificate — the whole point of Redfish over legacy protocols is that it is TLS-encrypted and verifiable. Basic auth is also supported and is fine for one-off calls, but it sends the password on every request and creates a new session each time, which fills the session table on some firmware versions and causes intermittent 503 responses. Session tokens are the supported path for anything automated.

The endpoints worth memorising

  • /redfish/v1/Systems/System.Embedded.1 — inventory, power state, boot order, BIOS attribute registry.
  • /redfish/v1/Systems/System.Embedded.1/Bios — GET current attributes, PATCH to change them, then apply through the job service.
  • /redfish/v1/Managers/iDRAC.Embedded.1 — iDRAC attributes, lifecycle controller logs, virtual console/media config.
  • /redfish/v1/UpdateService/FirmwareInventory — every firmware component with version and updateability.
  • /redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellLCService — operations unique to Dell, including Server Configuration Profile export/import.
  • /redfish/v1/TaskService/Tasks — the job queue that most write operations are asynchronous through; poll it until a task reaches Completed.

Typical automation workflows

# Power
curl -sk -H "X-Auth-Token: *** -X POST \
  https://10.0.0.10/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset \
  -d '{"ResetType":"On"}'

# Next one-time boot device
PATCH /redfish/v1/Systems/System.Embedded.1  {"Boot":{"BootSourceOverrideTarget":"Pxe"}}

# Firmware inventory for a fleet report
for h in $(cat idracs.txt); do
  curl -sk -H "X-Auth-Token: *** "https://$h/redfish/v1/UpdateService/FirmwareInventory?\$expand=." \
    | jq -r '.Members[] | "\(.Name) \(.Version)"'
done

Batch firmware inventory is the highest-value first automation: it answers “which servers are on a vulnerable BIOS” in seconds instead of a change-request cycle. Server Configuration Profile (SCP) export/import is the second: it captures BIOS, iDRAC and RAID configuration as a single file you can diff and restore after a board replacement.

Python and PowerShell Patterns

For anything beyond a few one-off curls the vendor library and a small wrapper are the fastest route. In Python, request a session, keep the token, and use a context manager so the session is deleted even when a call raises:

import requests

class Idrac:
    def __init__(self, host, user, password, verify=True):
        self.base = f"https://{host}/redfish/v1"
        self.verify = verify
        self.token = None
        self.sess = requests.Session()
        self.sess.verify = verify

    def login(self, user, password):
        r = self.sess.post(f"{self.base}/SessionService/Sessions",
                           json={"UserName": user, "Password": password})
        r.raise_for_status()
        self.token = r.headers["X-Auth-Token"]
        self.sess.headers.update({"X-Auth-Token": self.token})

    def firmware(self):
        data = self.sess.get(
            f"{self.base}/UpdateService/FirmwareInventory?$expand=.").json()
        return {m["Name"]: m.get("Version") for m in data["Members"]}

In PowerShell the same shape applies with Invoke-RestMethod. Skip certificate validation only in the lab with -SkipCertificateCheck (PowerShell 7) or a manual ServicePointManager callback on Windows PowerShell 5.1. The shipped Dell module wraps all of this behind set_iDRAC_script_session(), which prompts once for the IP, user, password, verification choice and whether to use an X-auth token, so a beginner can get valid sessions in three lines.

Use the vendor libraries instead of raw curl

Dell publishes iDRAC-Redfish-Scripting with Python and PowerShell samples covering BIOS, iDRAC, firmware, server and storage operations, plus an installable module (pip3 install IdracRedfishSupport) whose set_iDRAC_script_session() prompts once for IP, user, password, certificate verification and whether to use an X-auth token session. Prerequisites are modest: PowerEdge 12G and newer, iDRAC7/8 firmware 2.40.40.40+, iDRAC9 3.00.00.00+, Python 3.x with requests.

The samples cover the operations that otherwise take days to reverse-engineer: setting BIOS attributes and applying them, exporting and importing an SCP, updating firmware from a repository, and reading the LC log. Start from the closest sample and trim it, rather than writing the request bodies by hand.

Server Configuration Profile Workflows

SCP export (for example ExportSystemConfiguration via DellLCService) writes BIOS, iDRAC and storage settings into a single XML or JSON file. It is the fastest way to:

  • Capture a golden configuration from a known-good server and diff every other server against it.
  • Rebuild a replacement server after a board swap without manual BIOS entry.
  • Apply a consistent baseline across a rack before the OS is ever installed.

Treat the exported file as a secret: it can contain iDRAC credentials, iSCSI CHAP secrets and licence keys. Store it in the same vault you keep other infrastructure secrets in, not in a share next to the script.

Changing BIOS Attributes Safely with the Job Service

BIOS changes are two-phase. You PATCH the desired attributes, then you tell the job service to apply them - and on most firmware that means a reboot. Doing it wrong leaves the server with attributes set but not applied, which then silently disappears at the next power cycle.

# 1. Read the current registry and what is writable
GET  /redfish/v1/Registries/BiosAttributeRegistry/BiosAttributeRegistry

# 2. PATCH the attributes you want to change
PATCH /redfish/v1/Systems/System.Embedded.1/Bios
      {"Attributes":{"BootMode":"Uefi","ProcVirtualization":"Enabled"}}

# 3. Apply through the job service (reboot may be required)
POST /redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/DellManager.SetAttributes

Always read the attribute registry rather than guessing at names - the spelling of an attribute and its allowed values are firmware-version specific, and a wrong value is rejected with a 400 that does not always say which field was wrong. When the server is in a job queue, poll /redfish/v1/TaskService/Tasks until the task reports Completed before treating the change as done; a task that reaches Exception means the change was rejected and nothing was written.

Fleet Inventory in Python and PowerShell

The batch firmware query from the curl section scales up cleanly. In Python, wrap the session once and iterate the host list, writing one JSON per host so a partial run is still usable:

hosts = [l.strip() for l in open("idracs.txt") if l.strip()]
for host in hosts:
    d = Idrac(host, user, password, verify=True)
    try:
        d.login(user, password)
        print(host, d.firmware())
    except Exception as e:
        print(host, "ERR", e)

The PowerShell equivalent uses Invoke-RestMethod and a loop, and is what most Windows-first shops reach for because it needs no Python runtime on the management jump host:

$session = Invoke-RestMethod -SkipCertificateCheck -Method Post `
  -Uri "https://$host/redfish/v1/SessionService/Sessions" `
  -Body (@{UserName=$u;Password=$p} | ConvertTo-Json) -ContentType "application/json"
$hdr = @{ "X-Auth-Token" = $session.Headers.'X-Auth-Token' }
Invoke-RestMethod -SkipCertificateCheck -Headers $hdr `
  -Uri "https://$host/redfish/v1/UpdateService/FirmwareInventory?`$expand=." |
  Select-Object -ExpandProperty Members | Select-Object Name, Version

Run either pattern against a CSV of hosts and you have a firmware report you can diff week over week. The same wrapper then carries every other operation - power actions, SCP export, LC log retrieval - because they all share the session and the base URL.

Operating It at Scale, Safely

For a fleet, run these as an Ansible module or a cron job that writes results into your CMDB — the API is fast enough that polling 200 servers is a background task, not a project. Keep a few rules:

  • Never expose the Redfish endpoint to the general corporate network; it belongs on a dedicated out-of-band management segment.
  • Log every write - every PATCH, every Reset action, every SCP import - with the calling identity and the target, because these can power-cycle production hardware.
  • Rate-limit and serialise polling so a scheduled inventory run does not open sessions on every iDRAC at once.
  • Rotate iDRAC credentials through the API rather than leaving vendor defaults in place.

Related reading: iDRAC versus iLO versus IPMI, Ansible command modules for multi-vendor automation and pyATS Genie parsing and state diff. For a fleet-configuration backup pattern built around the same REST approach, see vCenter and ESXi configuration backup scripting, and for certificate handling on the management interfaces, OpenSSL certificate chain verification troubleshooting.

One final caution that catches teams out during a rollout: the Redfish resource paths are stable, but individual properties are added and deprecated between firmware versions. Pin your automation to the properties you actually consume, tolerate extra keys in the JSON rather than asserting an exact schema, and re-test the scripts after every iDRAC firmware upgrade - the same discipline you apply to a config template. Done that way, a single Python or PowerShell wrapper carries out-of-band management, firmware compliance and configuration capture for the whole PowerEdge fleet from one maintainable codebase.

原文链接:https://github.com/dell/iDRAC-Redfish-Scripting