はじめに
このドキュメントでは、Pythonを使用してRest APIを呼び出す例について説明します。
前提条件
このガイドで使用するツールとデバイスは次のとおりです。
- Cisco Firepower Threat Defense(FTD)
- シスコFirepowerデバイスマネージメント(FDM)
- Mac OS
- 崇高なテキスト
要件
次の項目に関する知識があることが推奨されます。
- HTTPS
- REST API
- Python
- Json
- Firepowerデバイスの管理
- [LDAP]
使用するコンポーネント
このドキュメントの情報は、次のソフトウェアとハードウェアのバージョンに基づいています。
- Python 3.11.4
- FDM APIバージョン6
- FTDv 7.3.1
このドキュメントの情報は、特定のラボ環境にあるデバイスに基づいて作成されました。このドキュメントで使用するすべてのデバイスは、クリアな(デフォルト)設定で作業を開始しています。本稼働中のネットワークでは、各コマンドによって起こる可能性がある影響を十分確認してください。
背景説明
このドキュメントの主な目的は、API呼び出しを行うPythonスクリプトを作成する手順を説明することです。
調整および構築される特定の機能は、LDAPおよび属性マップです。
このガイドでは、次のAPI呼び出しを行います。
GET:サーバーから情報を収集します
POST:サーバー上に新しいオブジェクトを作成します
PUT:サーバー上の既存のオブジェクトを更新します
削除:サーバーから既存のオブジェクトを削除します
設定
GET
既存のオブジェクトのデータを収集するREST API GETの例:
import requests
import json
import certifi
import urllib3
from pprint import pprint
from getpass import getpass
urllib3.disable_warnings()
#Data collection
u = input ('Input username: ')
p = getpass(prompt='Input password: ')
url = input('Input Hostname or IP address: ')
protocol = 'https://'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def auth():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
payload = {
'grant_type' : 'password',
'username' : u,
'password': p
}
response = requests.post(token_url, data=payload, verify=False)
#ONlY USE "verify=False" in a lab setting!
#Error Checking
if response.status_code == 400:
raise Exception("Error Received: {}".format(response.content))
else:
access_token = response.json()['access_token']
return access_token
token = auth()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def getactivedirectory():
uri = "/api/fdm/v6/object/realms"
ad_url = protocol+url+uri
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer {}".format(token)
}
response = requests.get(ad_url, headers=headers, verify=False)
if response.status_code == 200:
AD = response.json()
return AD
else:
print(response.status_code)
pass
pprint(getactivedirectory())
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def revoke():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer"
}
payload = {
'grant_type' : 'revoke_token',
"access_token": token,
"token_to_revoke": token,
}
response = requests.post(token_url, data=payload, verify=False)
if response.status_code == 200:
print("Access token revoked")
else:
print(response.status_code)
revoke()
POST
このセクションでは、新しいLDAP属性マップオブジェクトを作成するためにREST API POST要求を行う例について説明します。
import requests
import json
import certifi
import urllib3
from pprint import pprint
from getpass import getpass
urllib3.disable_warnings()
#Data collection
u = input ('Input username: ')
p = getpass(prompt='Input password: ')
url = input('Input Hostname or IP address: ')
protocol = 'https://'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def auth():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
payload = {
'grant_type' : 'password',
'username' : u,
'password': p
}
response = requests.post(token_url, data=payload, verify=False)
#WARNING ONLY USE "verify=False" in a lab setting!
#Error Checking
if response.status_code == 400:
raise Exception("Error Received: {}".format(response.content))
else:
access_token = response.json()['access_token']
return access_token
token = auth()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def postattributemap():
uri = "/api/fdm/v6/object/ldapattributemaps"
ad_url = protocol+url+uri
name = input('Object name> ')
group_policy = input('Group-Policy> ')
base = input('LDAP DN> ')
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer {}".format(token)
}
payload = {
"name": name,
"ldapAttributeMaps": [
{
"ldapName": "memberOf",
"ciscoName": "GROUP_POLICY",
"valueMappings": [
{
"ldapValue": base,
"ciscoValue": group_policy,
"type": "ldaptociscovaluemapping"
}
],
"type": "ldapattributemapping"
}
],
"type": "ldapattributemap"
}
data = json.dumps(payload)
response = requests.post(ad_url, headers=headers, data=data, verify=False)
if response.status_code == 200:
print(response.status_code)
print("Created LDAP attribute map")
map = response.json
return map
else:
print(response.status_code)
pprint(response.content)
pass
postattributemap()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def revoke():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer"
}
payload = {
'grant_type' : 'revoke_token',
"access_token": token,
"token_to_revoke": token,
}
response = requests.post(token_url, data=payload, verify=False)
if response.status_code == 200:
print("Access token revoked")
else:
print(response.status_code)
revoke()
PUT
このセクションでは、PUT Rest APIを呼び出すPythonスクリプトの例を示します。この関数は、LDAP属性マップを既存のActive Directory設定に追加します。
注:先に進む前に、オブジェクトの更新に必要な情報をGET関数で収集する必要があります。
URL1 Active Directoryレルム: /api/fdm/v6/object/realms/
URL2 LDAP属性マップ: /api/fdm/v6/object/ldapattributemaps
import requests
import json
import certifi
import urllib3
from pprint import pprint
from getpass import getpass
urllib3.disable_warnings()
#Data collection
u = input ('Input username: ')
p = getpass(prompt='Input password: ')
url = input('Input Hostname or IP address: ')
protocol = 'https://'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def auth():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
payload = {
'grant_type' : 'password',
'username' : u,
'password': p
}
response = requests.post(token_url, data=payload, verify=False)
#WARNING ONLY USE "verify=False" in a lab setting!
#Error Checking
if response.status_code == 400:
raise Exception("Error Received: {}".format(response.content))
else:
access_token = response.json()['access_token']
return access_token
token = auth()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def put():
objId = input('object id of active directory object> ')
uri = "/api/fdm/v6/object/realms/"
ad_url = protocol+url+uri+objId
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer {}".format(token)
}
#Place the GET response from the active directory here in "payload" along with the added "ldapAttributeMap", "id" and ""type": "ldapattributemap""
payload = {
"version": "p6ueo2w2aulkf",
"name": "Test",
"directoryConfigurations": [
{
"hostname": "{omitted}",
"port": 389,
"encryptionProtocol": "NONE",
"encryptionCert": None,
"interface": {
"version": "mjvylmnd52agk",
"name": "diagnostic",
"hardwareName": "Management0/0",
"id": "a46ef70c-06ca-11ee-9be1-bd712e622992",
"type": "physicalinterface"
},
"type": "directoryconfiguration"
}
],
"enabled": True,
"realmId": 3,
"dirUsername": "{omitted}",
"dirPassword": "*********",
"baseDN": "dc={omitted},dc=com",
"ldapAttributeMap": {
"id": "7fbf5798-27c9-11ee-a635-a1f4b2c2e66b",
"type": "ldapattributemap"
},
"adPrimaryDomain": "{omitted}.com",
"id": "5957a304-2662-11ee-a635-a5df7d28e8c4",
"type": "activedirectoryrealm"
}
data = json.dumps(payload)
response = requests.put(ad_url, headers=headers, data=data, verify=False)
if response.status_code == 200:
print("Updated Object")
else:
pprint("Error Received: {}".format(response.content))
pass
put()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def revoke():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer"
}
payload = {
'grant_type' : 'revoke_token',
"access_token": token,
"token_to_revoke": token,
}
response = requests.post(token_url, data=payload, verify=False)
if response.status_code == 200:
print("Access token revoked")
else:
print(response.status_code)
revoke()
削除
この項では、Active Directoryオブジェクトを削除するRest API DELETEの例について説明します。
import requests
import json
import certifi
import urllib3
from pprint import pprint
from getpass import getpass
urllib3.disable_warnings()
#Data collection
u = input ('Input username: ')
p = getpass(prompt='Input password: ')
url = input('Input Hostname or IP address: ')
protocol = 'https://'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def auth():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
payload = {
'grant_type' : 'password',
'username' : u,
'password': p
}
response = requests.post(token_url, data=payload, verify=False)
#ONlY USE "verify=False" in a lab setting!
#Error Checking
if response.status_code == 400:
raise Exception("Error Received: {}".format(response.content))
else:
access_token = response.json()['access_token']
return access_token
token = auth()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def delete():
objId = input('object id to delete> ')
uri = "/api/fdm/v6/object/realms/"
ad_url = protocol+url+uri+objId
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer {}".format(token)
}
response = requests.delete(ad_url, headers=headers, verify=False)
if response.status_code == 204:
print('Object removed')
else:
print("Error Received: {}".format(response.content))
pass
delete()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def revoke():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer"
}
payload = {
'grant_type' : 'revoke_token',
"access_token": token,
"token_to_revoke": token,
}
response = requests.post(token_url, data=payload, verify=False)
if response.status_code == 200:
print("Access token revoked")
else:
print(response.status_code)
revoke()
展開
このセクションでは、POST REST API呼び出しを使用して設定の変更を展開する例と、GET要求を使用して展開のステータスを確認する例について説明します。
import requests
import json
import certifi
import urllib3
from pprint import pprint
from getpass import getpass
urllib3.disable_warnings()
#Data collection
u = input ('Input username: ')
p = getpass(prompt='Input password: ')
url = input('Input Hostname or IP address: ')
protocol = 'https://'
x="0"
attempts=0
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def auth():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
payload = {
'grant_type' : 'password',
'username' : u,
'password': p
}
response = requests.post(token_url, data=payload, verify=False)
#ONlY USE "verify=False" in a lab setting!
#Error Checking
if response.status_code == 400:
raise Exception("Error Received: {}".format(response.content))
else:
access_token = response.json()['access_token']
return access_token
token = auth()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def deploy():
uri = '/api/fdm/v6/operational/deploy'
deploy = protocol+url+uri
headers = headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer {}".format(token)
}
payload = {
"statusMessage": "string",
"cliErrorMessage": "string",
"state": "QUEUED",
"queuedTime": 0,
"startTime": 0,
"endTime": 0,
"statusMessages": [
"string"
],
"id": "string",
"name": "string",
"modifiedObjects": {},
"forceRefreshDeploymentData": False,
"type": "deploymentstatus"
}
data = json.dumps(payload)
response = requests.get(deploy, headers=headers, data=data,verify=False)
if response.status_code == 200:
print(response.status_code)
status = response.json()['items'][0]['statusMessage']
return status
else:
print(response.status_code)
pass
status = deploy()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def deploy2():
uri = '/api/fdm/v6/operational/deploy'
deploy = protocol+url+uri
headers = headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer {}".format(token)
}
payload = {
"statusMessage": "string",
"cliErrorMessage": "string",
"state": "QUEUED",
"queuedTime": 0,
"startTime": 0,
"endTime": 0,
"statusMessages": [
"string"
],
"id": "string",
"name": "string",
"modifiedObjects": {},
"forceRefreshDeploymentData": False,
"type": "deploymentstatus"
}
data = json.dumps(payload)
response = requests.post(deploy, headers=headers, data=data,verify=False)
if response.status_code == 200:
print(response.status_code)
print('Deploying')
else:
print(response.status_code)
pass
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def revoke():
uri = '/api/fdm/v6/fdm/token'
token_url = protocol+url+uri
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization":"Bearer"
}
payload = {
'grant_type' : 'revoke_token',
"access_token": token,
"token_to_revoke": token,
}
response = requests.post(token_url, data=payload, verify=False)
if response.status_code == 200:
print("Access token revoked")
else:
print(response.status_code)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
while True:
x = input("""
Press 1 for deployment status
Press 2 to deploy
Enter Exit to exit
> """).lower()
if x == "1":
deploy()
pprint('Status is: ' + status)
elif x == "2":
deploy2()
elif x == "exit":
break
revoke()
elif x != "1" or "2" or "exit":
attempts += 1
print("The options are 1, 2 or Exit only!")
if attempts == 3:
print('Closing the program')
revoke()
break
else:
raise Exception("Program shutting down")
確認
GET
このスクリプトを使用すると、次の図に示すように、HTTPコード応答「200」が受信され、出力が表示されます。
スクリプトからの出力
PUT
図に示すように、FDM GUIで新しい配置を正常に実行する準備が整います。
FDM管理ページのスクリーンショット
HTTP応答コード200を受信して確認することもできる。
削除
FDM GUIで新しい配置が正常に実行される準備ができています。
HTTP応答コード204を受信して確認することもできる。
トラブルシュート
この項では、トラブルシューティングの方法について説明します。
HTTP応答コードは、確認された特定の問題について通知できます。
クライアントエラー4XX
400:不正な要求
401 – 許可されていません
403 – 禁止
404 – 見つかりません
408:要求タイムアウト
415:サポートされていないメディアタイプ
サーバエラー5xx
500:内部サーバエラー
501:未実装
502:ゲートウェイが正しくない
503:サービス使用不可
関連情報
RFC 2616:ハイパーテキスト転送プロトコル – HTTP/1.1
firepower脅威対策REST APIの概要 – FTD-APIリファレンスv6(FTD v7.2) – ドキュメント – Cisco Developer