通过python调用dnac API获取设备信息,此脚本可作为借鉴,当然通过API可以做的事情很多,例如推送配置、查看有线/无线在线数、查看接口配置。如果想查找多台设备做个for循环就可以了。
获取步骤如下:
- 首先获取token
- 通过对应的api页面,根据官方文档添加请求头(不同api会使用不同herders)
- 通过请求头,就会收到相应的response信息。
1. dnac_config.py里面包含ip、用户名、密码及基础api页面等
# When you assign username and password here you
# can import into multiple scripts
DNAC_USER = "<user>" #自行修改
DNAC_PASSWORD = "<password>" #自行修改
BASE_URL = '<IP>' #自行修改
AUTH_URL = '/dna/system/api/v1/auth/token'
SITE_HEALTH = '/dna/intent/api/v1/site-health'
NETWORK_HEALTH = '/dna/intent/api/v1/network-health'
NETWORK_DEVICE = '/dna/intent/api/v1/network-device'
CLIENT_HEALTH = '/dna/intent/api/v1/client-health'
2. get_device_list.py 执行脚本获取设备信息
import requests
from requests.auth import HTTPBasicAuth
from dnac_config import DNAC_USER, DNAC_PASSWORD,BASE_URL,AUTH_URL,SITE_HEALTH,NETWORK_DEVICE,NETWORK_HEALTH,CLIENT_HEALTH
def get_auth_token():
"""
Building out Auth request. Using requests.post to make a call to the Auth Endpoint
"""
# url = 'https://<IP>/dna/system/api/v1/auth/token' # Endpoint URL
resp = requests.post(BASE_URL + AUTH_URL, auth=HTTPBasicAuth(DNAC_USER, DNAC_PASSWORD), verify=False) # Make the POST Request
token = resp.json()['Token'] # Retrieve the Token
return token # Create a return statement for the Token
def get_device_list():
"""
Building out function to retrieve list of devices. Using requests.get to make a call to the network device Endpoint
"""
token = get_auth_token() # Get Token
# url = "https://<IP>/api/v1/network-device"
hdr = {'x-auth-token': token, 'content-type' : 'application/json'}
resp = requests.get(BASE_URL + NETWORK_DEVICE, headers=hdr, verify=False) # Make the Get Request
device_list = resp.json()
print_device_list(device_list)
def print_device_list(device_json):
print("{0:42}{1:17}{2:12}{3:18}{4:12}{5:16}{6:15}".
format("hostname", "mgmt IP", "serial","platformId", "SW Version", "role", "Uptime"))
for device in device_json['response']:
uptime = "N/A" if device['upTime'] is None else device['upTime']
if device['serialNumber'] is not None and "," in device['serialNumber']:
serialPlatformList = zip(device['serialNumber'].split(","), device['platformId'].split(","))
else:
serialPlatformList = [(device['serialNumber'], device['platformId'])]
for (serialNumber, platformId) in serialPlatformList:
print("{0:42}{1:17}{2:12}{3:18}{4:12}{5:16}{6:15}".
format(device['hostname'],
device['managementIpAddress'],
serialNumber,
platformId,
device['softwareVersion'],
device['role'], uptime))
if __name__ == "__main__":
get_device_list()