簡介
本文檔介紹使用Python進行Rest API呼叫的示例。
必要條件
本指南中使用的工具和裝置包括:
- Cisco Firepower威脅防禦(FTD)
- Cisco Firepower Device Management(FDM)
- Mac OS
- 崇高文本
需求
思科建議您瞭解以下主題:
- HTTPS
- Rest API
- Python
- Json
- Firepower裝置管理
- LDAP
採用元件
本文中的資訊係根據以下軟體和硬體版本:
- Python 3.11.4
- FDM API版本6
- FTDv 7.3.1
本文中的資訊是根據特定實驗室環境內的裝置所建立。文中使用到的所有裝置皆從已清除(預設)的組態來啟動。如果您的網路運作中,請確保您瞭解任何指令可能造成的影響。
背景資訊
本文檔的主要目的是指導您完成建立Python指令碼以進行API呼叫的步驟。
要調整和構建的特定功能是LDAP和屬性對映。
本指南中的API呼叫包括:
GET:從伺服器收集資訊
POST:在伺服器上建立新對象
PUT:更新伺服器上的現有對象
DELETE:從伺服器中刪除現有對象
設定
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
本部分介紹建立REST API POST請求以建立新LDAP屬性對映對象的示例:
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/ldapattributempps
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