Hit ISE's ERS API with PowerShell

Introduction

If you want to operate the API easily, you will often use cURL, Postman, HTTP Client provided by various programming languages, etc., but it may not be possible to prepare such an environment due to various restrictions. Is it not?

In this post, I will introduce the API of Cisco Identity Services Engine (hereinafter referred to as ISE) that you can operate REST API at least with a Windows terminal (PowerShell).

Both use the ʻInvoke-WebRequest` command, which is available by default in PowerShell. For reference, an example of implementing the same operation in Python is also shown.

environment

・ Windows 10 Pro -PowerShell version 5.1 (default settings after installing Windows) · Cisco ISE version 2.6

Preparation

See Qiita Articles or DevNet Articles.

What you want to do ① Get information by GET

PowerShell implementation example


#Processing to avoid SSL errors
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


#Variable definition
$username = 'ersadmin' # ERS Admin Username
$password = 'XXXX' # ERS Admin Password
$url = 'https://X.X.X.X:9060/ers/config/internaluser/' # X.X.X.X => ISE's IP address
$credPair = "$($username):$($password)"
 
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
 hu
$headers = @{
'Authorization'= "Basic $encodedCredentials"; 
'Accept'= 'application/json'; 
'cache-control'= 'no-cache'
 }

#API call
$responseData = Invoke-WebRequest -Uri $url -Method Get -Headers $headers -UseBasicParsing

#Example of confirmation method
return $responseData
return $responseData.StatusCode
return $responseData.Header
return $responseData.RawContent
return $responseData.Content

By default, PowerShell provides the command ʻInvoke-RestMethod in addition to ʻInvoke-WebRequest as an HTTP client. In order to display the response header and contents in a form that is easy for people to see like this time, it is better to add -UserBasicParsing to ʻInvoke-WebRequest, and if you want to handle the return value directly and do something, ʻInvoke -RestMethod seems to be useful. What is the difference between here and [here](https://www.it-swarm.dev/ja/windows/invokewebrequest and invokerestmethod? / 944432281 /) is also helpful.

Reference Python implementation example

Use Requests library for API calls on python3.7 (mac) (this is simpler)


import requests
import json
import base64

host = "X.X.X.X" # ISE's IP address
user = "ersadmin" # ERS Admin Username
password = "XXXXXX" # ERS Admin Password

creds = str.encode(':'.join((user, password)))
encodedAuth = bytes.decode(base64.b64encode(creds))

headers = {
    'accept': "application/json",
    'authorization': " ".join(("Basic",encodedAuth)),
    'cache-control': "no-cache",
    }

url = "https://{}:9060".format(host) + "/ers/config/internaluser/"

r = requests.get(url, headers=headers,verify=False) #Enable SSL error avoidance option because ISE uses self-signed certificate this time

data = r.json()

print(json.dumps(data, indent=4))

What you want to do ② Update information by PUT

PowerShell implementation example


#Processing to avoid SSL errors
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


#Variable definition
$username = 'ersadmin' # ERS Admin Username
$password = 'XXXX' # ERS Admin Password
$url = 'https://X.X.X.X:9060/ers/config/internaluser/' + "57d1fada-3ab6-4d62-94eb-9b77be36dc7e"  # X.X.X.X => ISE's IP address +The target user's ID becomes the URL

$credPair = "$($username):$($password)"
 
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
 

#Content in the header-Add type
$headers = @{
'Authorization'= "Basic $encodedCredentials"; 
'Accept'= 'application/json'; 
'cache-control'= 'no-cache';
'content-type'= 'application/json'
 }

#Body definition. The parameter is the id of the account you want to change, name,Minimum password required
$body = @{
"InternalUser" = @{
"id" = "57d1fada-3ab6-4d62-94eb-9b77be36dc7e";
"name" = "user1";
"password"="Password123"
}
} | convertTo-Json

#API request
$responseData = Invoke-WebRequest -Uri $url -Method PUT -Headers $headers -Body $body -UseBasicParsing

#Confirmation method
return $responseData.RawContent
return $responseData
return $responseData.StatusCode
return $responseData.Header
return $responseData.Content

Reference Python implementation example


import requests
import json
import base64

host = "X.X.X.X" # ISE's IP address
user = "ersadmin" # ERS Admin Username
password = "XXXXXX" # ERS Admin Password
user_id = "57d1fada-3ab6-4d62-94eb-9b77be36dc7e" #ID of the user to be updated

creds = str.encode(':'.join((user, password)))
encodedAuth = bytes.decode(base64.b64encode(creds))

headers = {
    'accept': "application/json",
    'content-type': "application/json",
    'authorization': " ".join(("Basic",encodedAuth)),
    'cache-control': "no-cache",
    }

req_body_json = """  {{
    "InternalUser" : {{
        "id" : "{}",
        "name" : "user1",
        "password" : "Password123",
        "customAttributes" : {{
        }}
    }}
}}
""".format(user_id,user_name,new_passwd)


url = "https://{}:9060".format(host) + "/ers/config/internaluser/{}".format(id)

r = requests.put(url, headers=headers, data=req_body_json, verify=False) 

data = r.json()

print(json.dumps(data, indent=4))

reference

How to do Basic authentication in PowerShell https://pallabpain.wordpress.com/2016/09/14/rest-api-call-with-basic-authentication-in-powershell/

DevNet Cisco ISE ERS API Reference Guide https://developer.cisco.com/docs/identity-services-engine/

ERS API (External RESTful Services API) https://www.cisco.com/c/en/us/td/docs/security/ise/2-6/api_ref_guide/api_ref_book/ise_api_ref_ers1.html

Python beginner wrote a script using ISE ERS API https://qiita.com/naixia/items/5c521183c2b606a891b1

What is the difference between Invoke-WebRequest and Invoke-RestMethod? https://www.it-swarm.dev/ja/windows/invokewebrequestとinvokerestmethodの違いは何ですか?/944432281/

Recommended Posts

Hit ISE's ERS API with PowerShell
Hit Zabbix API (1.8, 2.0)
Hit the Twitter API after Oauth authentication with Django
Hit Mastodon's API in Python
Image download with Flickr API
Use Trello API with python
Create an API with Django
Use Twitter API with Python
API with Flask + uWSGI + Nginx
venv environment with windows powershell
Web API with Python + Falcon
Support yourself with Twitter API
Call the API with python3.
Use subsonic API with python3
Successful update_with_media with twitter API
[PowerShell] Morphological analysis with SudachiPy
Qiita API Oauth with Django
Get ranking with Rakuten API