Dans le cadre de la documentation associée à ce produit, nous nous efforçons d’utiliser un langage exempt de préjugés. Dans cet ensemble de documents, le langage exempt de discrimination renvoie à une langue qui exclut la discrimination en fonction de l’âge, des handicaps, du genre, de l’appartenance raciale de l’identité ethnique, de l’orientation sexuelle, de la situation socio-économique et de l’intersectionnalité. Des exceptions peuvent s’appliquer dans les documents si le langage est codé en dur dans les interfaces utilisateurs du produit logiciel, si le langage utilisé est basé sur la documentation RFP ou si le langage utilisé provient d’un produit tiers référencé. Découvrez comment Cisco utilise le langage inclusif.
Cisco a traduit ce document en traduction automatisée vérifiée par une personne dans le cadre d’un service mondial permettant à nos utilisateurs d’obtenir le contenu d’assistance dans leur propre langue. Il convient cependant de noter que même la meilleure traduction automatisée ne sera pas aussi précise que celle fournie par un traducteur professionnel.
Ce document décrit un exemple d'utilisation de Python pour effectuer des appels d'API Rest.
Les outils et périphériques utilisés dans le guide sont les suivants :
Cisco vous recommande de prendre connaissance des rubriques suivantes :
Les informations contenues dans ce document sont basées sur les versions de matériel et de logiciel suivantes :
The information in this document was created from the devices in a specific lab environment. All of the devices used in this document started with a cleared (default) configuration. Si votre réseau est en ligne, assurez-vous de bien comprendre l’incidence possible des commandes.
L'objectif principal de ce document est de vous guider à travers les étapes de création d'un script Python pour passer des appels d'API.
La fonctionnalité spécifique à ajuster et à créer est LDAP et les mappages d'attributs.
Les appels d'API effectués dans le guide sont les suivants :
GET : collecte d'informations à partir du serveur
POST : Créer un nouvel objet sur le serveur
PUT : met à jour un objet existant sur le serveur
DELETE : suppression d'un objet existant du serveur
Rest API GET exemple pour collecter des données sur des objets existants :
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()
Cette section décrit un exemple de demande REST API POST pour créer un objet de mappage d'attribut 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()
Cette section montre un exemple de script Python effectuant un appel de l'API PUT Rest. Cette fonction ajoute le mappage d'attributs LDAP aux configurations Active Directory existantes.
Remarque : avant de continuer, les informations nécessaires à la mise à jour de l'objet doivent être collectées via la fonction GET.
URL1 Domaines Active Directory : /api/fdm/v6/object/realms/
Mappage d'attribut LDAP URL2 : /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()
Cette section décrit un exemple de suppression de l'API Rest pour supprimer l'objet Active Directory :
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()
Cette section décrit un exemple de déploiement de modifications de configuration via un appel API POST REST et de confirmation de l'état des déploiements avec une requête 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")
Avec ce script, une réponse de code HTTP "200" est reçue et le résultat est présenté, comme illustré dans l'image ci-dessous.
Un nouveau déploiement est prêt sur l'interface utilisateur graphique de FDM avec des tentatives réussies, comme illustré dans l'image.
La confirmation peut également être confirmée en recevant un code de réponse HTTP 200.
Un nouveau déploiement est prêt sur l'interface utilisateur graphique de FDM avec des tentatives réussies.
La confirmation peut également être confirmée par la réception d'un code de réponse HTTP 204.
Cette section décrit la procédure de dépannage.
Le code de réponse HTTP peut fournir des informations sur les problèmes spécifiques rencontrés :
Erreurs client 4XX
400- Requête incorrecte
401 - Non autorisé
403- Interdit
404- Introuvable
408- Délai de demande
415 - Type de support non pris en charge
Erreurs de serveur 5xx
500- Erreur interne du serveur
501 - Non implémenté
502- Passerelle incorrecte
503- Service indisponible
Révision | Date de publication | Commentaires |
---|---|---|
2.0 |
04-Nov-2023 |
Correction de la faute de frappe. Changement de "royaumes" en "royaumes" |
1.0 |
24-Jul-2023 |
Première publication |