Tuesday, December 3, 2019

Working with iDRAC9 Redfish API using PowerShell - Part 3

In this article, I will explain how to access the iDRAC Redfish API using session-based authentication.


[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [String]$idrac_ip
)

#To fix the connection issues to iDRAC REST API
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
        }
    }
"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11

#Get iDRAC creds
$Credentials = Get-Credential -Message "Enter iDRAC Creds"

$creds_json = '{"UserName": "$($Credentials.UserName)", "Password": "$($Credentials.GetNetworkCredential().Password)"}'
$creds_json = $ExecutionContext.InvokeCommand.ExpandString($creds_json)

#Using Invoke-WebRequest
try {
    $result1 = Invoke-WebRequest -Uri "https://$($idrac_ip)/redfish/v1/Sessions " -Method POST -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $creds_json -Verbose
}
catch {
    Write-Error -Message "Failed to invoke the API! Incorrect creds!"
    $PSCmdlet.ThrowTerminatingError($PSItem)
}

$auth_head = @{
"X-Auth-Token" = $result1.Headers.'X-Auth-Token'
"accept" = "application/json" }

#URI to get basic system info
$u1 = "https://$($idrac_ip)/redfish/v1/Systems/System.Embedded.1"

#Using Invoke-RestMethod
try {
    $output = Invoke-RestMethod -Uri $u1 -Method Get -Headers $auth_head -ContentType 'application/json' -Verbose
}
catch {
    Write-Error -Message "Failed to invoke the API! Incorrect creds!"
    $PSCmdlet.ThrowTerminatingError($PSItem)
}

Write-Output "`nBasic System Info:" $output



Hope it was useful. Cheers!

Related posts

Working with iDRAC9 Redfish API using PowerShell - Part 1

Working with iDRAC9 Redfish API using PowerShell - Part 2


References

iDRAC9 Redfish API guide

No comments:

Post a Comment