ePub(328.5 KB) iPhone, iPad, Android, Sony Reader 또는 Windows Phone의 다양한 앱에서 보기
Mobi (Kindle)(246.6 KB) Kindle 디바이스에서 보기 또는 다양한 디바이스의 Kindle 앱에서 보기
업데이트:2024년 8월 6일
문서 ID:222278
편견 없는 언어
본 제품에 대한 문서 세트는 편견 없는 언어를 사용하기 위해 노력합니다. 본 설명서 세트의 목적상, 편견 없는 언어는 나이, 장애, 성별, 인종 정체성, 민족 정체성, 성적 지향성, 사회 경제적 지위 및 교차성에 기초한 차별을 의미하지 않는 언어로 정의됩니다. 제품 소프트웨어의 사용자 인터페이스에서 하드코딩된 언어, RFP 설명서에 기초한 언어 또는 참조된 서드파티 제품에서 사용하는 언어로 인해 설명서에 예외가 있을 수 있습니다. 시스코에서 어떤 방식으로 포용적인 언어를 사용하고 있는지 자세히 알아보세요.
이 번역에 관하여
Cisco는 전 세계 사용자에게 다양한 언어로 지원 콘텐츠를 제공하기 위해 기계 번역 기술과 수작업 번역을 병행하여 이 문서를 번역했습니다. 아무리 품질이 높은 기계 번역이라도 전문 번역가의 번역 결과물만큼 정확하지는 않습니다. Cisco Systems, Inc.는 이 같은 번역에 대해 어떠한 책임도 지지 않으며 항상 원본 영문 문서(링크 제공됨)를 참조할 것을 권장합니다.
Cisco는 이 개발 설계에 대한 공식적인 지원을 제공하지 않습니다. API가 애플리케이션과 어떻게 상호 작용하는지 쉽게 이해할 수 있도록 참조용으로 작성되었습니다. 사용자는 이 설계를 프로덕션 수준의 구현을 위한 근거가 아닌 교육적 목적으로만 사용해야 합니다. 이 문서에 제시된 코드를 실행하는 것은 사용자의 책임이며, Cisco는 그 사용으로 인해 발생하는 모든 문제에 대해 어떠한 책임도 명시적으로 부인합니다.
소개
이 문서에서는 Python 및 REST API를 사용하여 대상 목록에서 가능한 모든 작업을 수행하는 방법에 대해 설명합니다.
이 스크립트에서는client_id및 을client_secretAPI KeyKey Secret각각 과 로 대체하십시오.
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)
성과:
이 스크립트의 출력은 다음과 같아야 합니다.
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
이 프로그램이 성공적으로 실행되면 처음에 Cookie(쿠키)에 대한 질문이 표시됩니다Cookie Already Generated? (Y/N). 이 질문을 하는 이유는 일단 생성된 쿠키가 3600초(1시간) 동안 유효하기 때문에 쿠키를 여러 번 생성하지 않도록 하기 위해서입니다. 또는y를 입력하면 새Y쿠키가 생성되지 않습니다. 그러나 를nN입력하거나 입력하면 새 쿠키가 생성되어 동일한 디렉토리/폴더에 있는 로컬 텍스트 파일에 저장됩니다. 이 파일의 쿠키는 후속 요청에 사용됩니다.
오류
DestinationList ID를 언급해야 하는 작업에 대해 잘못된 ID를 입력하면 이 오류가 발생할 수 있습니다.
{'message': 'no Route matched with those values'}
DestinationList를 만드는 동안 255자를 초과하는 DestinationList의 이름을 언급하면 다음 오류가 표시됩니다.
Secure Access API 엔드포인트는 HTTP 응답 코드를 사용하여 API 요청의 성공 또는 실패를 나타냅니다. 일반적으로 2xx 범위의 코드는 성공을 나타내고, 4xx 범위의 코드는 제공된 정보에서 발생한 오류를 나타내며, 5xx 범위의 코드는 서버 오류를 나타낸다. 문제를 해결하기 위한 접근 방식은 수신된 응답 코드에 따라 달라집니다.