Wednesday, September 22, 2021

Get NetScaler HA status using PowerShell

I had the need today to pull the HA status from numerous NetScalers before doing some maintenance.  Instead of logging in to each device, this script takes advantage of the NetScaler API to pull and summarize this information.  Hope this helps someone...

if (-not $login){
    $login = @(
        @{
            name = "somedomain"
            credential = Get-Credential -Message somedomain
        },
        @{
            name = "root"
            credential = Get-Credential -Message nsroot -UserName nsroot
        }
    )
}

$clusters = @(
    @{
        nodes = @(
            "nsr1.domain.local"
            "nsr3.domain.local"
        )
        credential = "somedomain"
    },
    @{
        nodes = @(
            "nsr1-fe.domain.local.remote"
            "nsr3-fe.domain.local.remote"
        )
        credential = "root"
    }
)

$result = foreach($cluster in $clusters){

    # Build login object
    $cred = $login | Where-Object {$_.name -eq $cluster.credential}
    $auth = @{ login= @{ username = $cred.credential.UserName; password = $cred.credential.GetNetworkCredential().Password } }

    # Enumerate nodes
    foreach($node in $cluster.nodes){

        Write-Verbose ("Working on node {0} with credential {1}" -f $node, $cred.name) -Verbose

        # Get auth token from NSR
        $token = Invoke-RestMethod -Uri ("https://{0}/nitro/v1/config/login" -f $node) -Method Post -Body ($auth | ConvertTo-Json) -ContentType "application/json"

        # Build auth session cookie
        $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
        $cookie = New-Object System.Net.Cookie 
        $cookie.Name = "NITRO_AUTH_TOKEN"
        $cookie.Value = $token.sessionid
        $cookie.Domain = $node
        $session.Cookies.Add($cookie)

        # Get NSR HA configuration
        $hainfo = Invoke-RestMethod -Uri ("https://{0}/nitro/v1/config/hanode" -f $node) -WebSession $session -Method Get

        # Log off session
        Invoke-RestMethod -Uri ("https://{0}/nitro/v1/config/logout" -f $node) -WebSession $session -Method Post -Body (@{logout = @{} } | ConvertTo-Json) -ContentType "application/json"

        [PSCustomObject]@{
            NodeName = $node
            NodeIP =  $hainfo.hanode.ipaddress -join ', '
            HAStatus = $hainfo.hanode.hastatus -join ', '
            State = $hainfo.hanode.state -join ', '
        }
    }
}

$result | Format-Table -AutoSize

No comments:

Post a Comment