PDF(484.9 KB) Ver no Adobe Reader em vários dispositivos
ePub(332.3 KB) Ver em vários aplicativos no iPhone, iPad, Android, Sony Reader ou Windows Phone
Mobi (Kindle)(250.8 KB) Ver no dispositivo Kindle ou no aplicativo Kindle em vários dispositivos
Atualizado:6 de agosto de 2024
ID do documento:222278
Linguagem imparcial
O conjunto de documentação deste produto faz o possível para usar uma linguagem imparcial. Para os fins deste conjunto de documentação, a imparcialidade é definida como uma linguagem que não implica em discriminação baseada em idade, deficiência, gênero, identidade racial, identidade étnica, orientação sexual, status socioeconômico e interseccionalidade. Pode haver exceções na documentação devido à linguagem codificada nas interfaces de usuário do software do produto, linguagem usada com base na documentação de RFP ou linguagem usada por um produto de terceiros referenciado. Saiba mais sobre como a Cisco está usando a linguagem inclusiva.
Sobre esta tradução
A Cisco traduziu este documento com a ajuda de tecnologias de tradução automática e humana para oferecer conteúdo de suporte aos seus usuários no seu próprio idioma, independentemente da localização.
Observe que mesmo a melhor tradução automática não será tão precisa quanto as realizadas por um tradutor profissional.
A Cisco Systems, Inc. não se responsabiliza pela precisão destas traduções e recomenda que o documento original em inglês (link fornecido) seja sempre consultado.
Informamos que a Cisco não fornece suporte oficial para este projeto de desenvolvimento. Ele foi projetado apenas como um exemplo de referência para facilitar a compreensão de como a API faz interface com aplicativos. Os usuários devem empregar este projeto apenas para fins educacionais e não como base para a implementação em nível de produção. A execução do código apresentado neste artigo é por sua conta e risco, e a Cisco se isenta expressamente de qualquer responsabilidade por quaisquer problemas decorrentes de seu uso.
Introdução
Este documento descreve como executar todas as operações possíveis em listas de destino usando Python e REST API.
Pré-requisitos
A Cisco recomenda que você tenha conhecimento destes tópicos:
Python
API REST
Acesso seguro da Cisco
Requisitos
Estes requisitos devem ser cumpridos antes de prosseguir:
Conta de usuário do Cisco Secure Access com a função de Administrador Completo.
Conta do Cisco Security Cloud Single Sign On (SCSO) para entrar no Secure Access.
As informações neste documento são baseadas nestas versões de software e hardware:
Painel de acesso seguro
Python 3. x
As informações neste documento foram criadas a partir de dispositivos em um ambiente de laboratório específico. Todos os dispositivos utilizados neste documento foram iniciados com uma configuração (padrão) inicial. Se a rede estiver ativa, certifique-se de que você entenda o impacto potencial de qualquer comando.
Configurar
Há várias maneiras de gravar esse código considerando vários aspectos, como Tratamento de erros, validade do token (3600 segundos) e assim por diante.
Certifique-se de que estas bibliotecas Python estejam instaladas antes de executar o script:
Certifique-se de substituir oclient_ide oclient_secretpelo seuAPI KeyeKey Secretneste script, respectivamente.
from oauthlib.oauth2 import BackendApplicationClient
from oauthlib.oauth2 import TokenExpiredError
from requests_oauthlib import OAuth2Session
from requests.auth import HTTPBasicAuth
import time
import requests
import pprint
import json
def fetch_headers(BToken):
BT = f"Bearer {BToken}"
headers = { 'Authorization':BT,
"Content-Type": "application/json",
"Accept": "application/json"
}
return headers
# GET OAUTH 2.0 TOKEN
def getToken():
token_url = 'https://api.sse.cisco.com/auth/v2/token'
try:
#ASSIGN your API Key to the variable client_id and Secret Key to the variable client_secret
client_id = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url, auth=auth)
print("\n######Token Generated Successfully######\n")
return token
except e as Exception:
print(f"Encountered an error while Fetching the TOKEN :: {e}")
# 1 - GET DESTINATION LISTS
def fetch_destinationlists(h):
url = "https://api.sse.cisco.com/policies/v2/destinationlists"
try:
response = requests.request('GET', url, headers=h)
json_object = json.loads(response.content)
#pprint.pprint(json_object)
x=1
for item in json_object["data"]:
print(f"Destination List : {x}")
pprint.pprint(f"Name : {item['name']}")
pprint.pprint(f"ID : {item['id']}")
#pprint.pprint(f"Destination Count : {item['meta']['destinationCount']}")
print("\n")
x+=1
except e as Exception:
print(f"Encountered an Error while Fetching the Destination Lists :: {e}")
# 2 - GET DESTINATION LIST
def get_destinationlist(h):
try:
choice = input("Enter the ID of the DestinationList:: ")
url = "https://api.sse.cisco.com/policies/v2/destinationlists/" + choice
response = requests.request('GET', url, headers=h)
json_object = json.loads(response.content)
print("\n\n")
pprint.pprint(json_object)
print("\n\n")
except e as Exception:
print(f"Encountered an Error while Fetching the Destination List Details :: {e}")
# 3 - CREATE DESTINATION LIST
def create_destinationlist(h):
url = "https://api.sse.cisco.com/policies/v2/destinationlists"
try:
naav = input("Name of the DestinationList :: ")
payload = {
"access": "none",
"isGlobal": False,
"name": naav,
}
response = requests.request('POST', url, headers=h, data = json.dumps(payload))
json_object = json.loads(response.content)
print("\n\n")
pprint.pprint(json_object)
print("\n\n")
except e as Exception:
print(f"Encountered an Error while Creating the Destination List :: {e}")
# 4 - UPDATE DESTINATION LIST NAME
def patch_destinationlist(h):
try:
choice = input("Enter the ID of the DestinationList for changing it's name :: ")
url = "https://api.sse.cisco.com/policies/v2/destinationlists/" + choice
naav = input("Enter New Name :: ")
payload = {"name": naav}
response = requests.request('PATCH', url, headers=h, data = json.dumps(payload))
json_object = json.loads(response.content)
print("\n\n")
pprint.pprint(json_object)
print("\n\n")
except e as Exception:
print(f"Encountered an Error while Updating the Destination List :: {e}")
# 5 - DELETE DESTINATION LIST
def delete_destinationlist(h):
try:
choice = input("Enter the ID of the DestinationList for DELETION :: ")
url = "https://api.sse.cisco.com/policies/v2/destinationlists/" + choice
response = requests.request('DELETE', url, headers=h)
json_object = json.loads(response.content)
print("\n\n")
pprint.pprint(json_object)
print("\n\n")
except Exception as e:
print(f"Encountered an Error while Deleting the Destination List :: {e}")
# 6 - GET DESTINATIONS FROM A DESTINATION LIST
def fetch_detail(h):
try:
choice = input("DestinationList ID: ")
url2 = "https://api.sse.cisco.com/policies/v2/destinationlists/" + choice + "/destinations"
response = requests.request('GET', url2, headers=h)
print("\n")
json_dest = json.loads(response.content)
pprint.pprint(json_dest)
print("\n\n")
except e as Exception:
print(f"Encountered an Error while Fetching the Destinations from the Destination List :: {e}")
# 7 - ADD DESTINATIONS TO A DESTINATION LIST
def add_destinations(h):
try:
choice = input("Enter the ID of the DestinationList :: ")
url = "https://api.sse.cisco.com/policies/v2/destinationlists/" + choice + "/destinations"
destination_to_add = input("\nEnter the destination that you want to add :: ")
payload = [{"destination": destination_to_add}]
response = requests.request('POST', url, headers=h, data = json.dumps(payload))
print("\n")
json_dest = json.loads(response.content)
pprint.pprint(json_dest)
print("\n\n")
except e as Exception:
print(f"Encountered an Error while Adding the Destination to the Destination List :: {e}")
# 8 - DELETE DESTINATIONS FROM DESTINATION LIST
def delete_entry(h):
try:
choice_del = input("\nCONFIRM DestinationList ID from which you want to delete the Destination :: ")
url3 = "https://api.sse.cisco.com/policies/v2/destinationlists/" + choice_del + "/destinations/remove"
dest = int(input("ID of the Destination that you want to remove: "))
payload = f"[{dest}]"
response = requests.request('DELETE', url3, headers=h, data=payload)
json_del = json.loads(response.content)
print("\n\n")
pprint.pprint(json_del)
print("\n\n")
except e as Exception:
print(f"Encountered an Error while Deleting a Destination from the Destination List :: {e}")
#FETCH COOKIE
possess_cookie = " "
while possess_cookie not in ["Y","y","N","n"]:
possess_cookie = input("Token Already Generated? (Y/N) :: ")
if possess_cookie.upper() =="N":
cook = getToken()
with open("cookie.txt","w") as wr:
wr.writelines(cook["access_token"])
# print(f"Access Token = {cook["access_token"]}")
#FETCH HEADERS
with open("cookie.txt","r") as ree:
h = fetch_headers(ree.readline())
print("\n")
while True:
action = input("""Available operations:
1. Get Destination Lists
2. Get Destination List
3. Create Destination List
4. Update Destination List Name
5. Delete Destination List
6. Get Destinations from Destination List
7. Add Destinations to a Destination List
8. Delete Destinations from Destination List
9. Exit
Enter Your Choice :: """)
print("\n")
operation = action.replace(" ","")
if operation == "1":
fetch_destinationlists(h)
elif operation == "2":
fetch_destinationlists(h)
get_destinationlist(h)
elif operation == "3":
create_destinationlist(h)
elif operation == "4":
fetch_destinationlists(h)
patch_destinationlist(h)
elif operation == "5":
fetch_destinationlists(h)
delete_destinationlist(h)
elif operation == "6":
fetch_destinationlists(h)
fetch_detail(h)
elif operation == "7":
fetch_destinationlists(h)
add_destinations(h)
elif operation == "8":
fetch_destinationlists(h)
fetch_detail(h)
delete_entry(h)
elif operation == "9":
break
else:
print("\n")
print("==========INCORRECT INPUT==========")
print("\n")
print("Thank You!!! Good Bye!!!")
time.sleep(5)
Saída:
A saída deste script deve ser semelhante a:
Cookie Already Generated? (Y/N) :: y
Available operations:
1. Get Destination Lists
2. Get Destination List
3. Create Destination List
4. Update Destination List Name
5. Delete Destination List
6. Get Destinations from Destination List
7. Add Destinations to a Destination List
8. Delete Destinations from Destination List
9. Exit
Enter Your Choice ::
Token Already Generated? (Y/N) :: y
Available operations:
1. Get Destination Lists
2. Get Destination List
3. Create Destination List
4. Update Destination List Name
5. Delete Destination List
6. Get Destinations from Destination List
7. Add Destinations to a Destination List
8. Delete Destinations from Destination List
9. Exit
Enter Your Choice :: 1
Uma vez que este programa é executado com sucesso, uma pergunta está sendo feita no início sobre o Cookie -Cookie Already Generated? (Y/N). O motivo para fazer essa pergunta é garantir que você não gere o cookie várias vezes, pois um cookie, uma vez gerado, é válido por 3600 segundos (1 hora). Se você digitaryouY, um novo cookie não será gerado. No entanto, se você digitarnouN, um novo cookie será gerado e salvo em um arquivo de texto local no mesmo diretório/pasta. O cookie desse arquivo é usado em suas solicitações subsequentes.
Erros
Você poderá encontrar este erro se inserir uma ID incorreta para qualquer operação que exija a menção da ID da lista de destino:
{'message': 'no Route matched with those values'}
Ao criar uma DestinationList, se você mencionar o nome de DestinationList com mais de 255 caracteres, verá este erro:
Os pontos de extremidade da API Secure Access usam códigos de resposta HTTP para indicar o sucesso ou a falha de uma solicitação da API. Em geral, os códigos no intervalo 2xx indicam êxito, os códigos no intervalo 4xx indicam um erro resultante das informações fornecidas e os códigos no intervalo 5xx indicam erros de servidor. A abordagem para resolver o problema dependeria do código de resposta recebido: