def GetPortList(switchX):
    # Connecting to DNAC
    global dnac
    dnac = api.DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                            version=DNAC_VERSION,
                            verify=False)
    switches = GetSwitchList()
    ports = [
        "{:<30}{:<15}{:<21}{:<15}".format("Interface Name", "Admin",
                                          "Operational", "Vlan ID")
    ]
    for switch in switches:
        if (switch['hostname'].lower()
                == switchX.lower()) or (switch['managementIpAddress']
                                        == switchX):
            interfaces = dnac.devices.get_device_interfaces_by_specified_range(
                device_id=switch['id'], records_to_return=500,
                start_index=1)['response']
            for interface in interfaces:
                if interface['portType'] == 'Ethernet Port':
                    if interface['vlanId'] == None:
                        interface['vlanId'] = ""
                    port = "{:<30}{:<15}{:^21}{:^15}".format(
                        interface['portName'], interface['adminStatus'],
                        interface['status'], interface['vlanId'])
                    ports.append(port)
    return (ports)
Exemplo n.º 2
0
def main():
    """
    Execution begins here.
    """

    # Create DNAC object, which automatically handles the token
    # request process. API docs in the link below, which may change:
    # https://dnacentersdk.readthedocs.io/en/latest/api/api.html
    dnac = api.DNACenterAPI(
        base_url="https://sandboxdnac.cisco.com",
        username="******",
        password="******",
    )

    # Use the devices.get_device_list() method to get a list of devices,
    # which is equivalent to the manual HTTP GET in the previous course
    devices = dnac.devices.get_device_list()

    # Debugging line; pretty-print JSON to see structure
    # import json; print(json.dumps(devices, indent=2))

    # Same exact loop from previous course, just get the device ID
    # and management IP agree printed in a single neat row
    for device in devices["response"]:
        print(f"ID: {device['id']}  IP: {device['managementIpAddress']}")
def main():
    dnac = api.DNACenterAPI(base_url="https://sandboxdnac.cisco.com",
                            username="******",
                            password="******")

    payload = {
        "cliTransport": "ssh",
        "enablePassword": "******",
        "ipAddress": ["192.168.1.1"],
        "password": "******",
        "snmpROCommunity": "readonly",
        "snmpRWCommunity": "readwrite",
        "snmpRetry": 1,
        "snmpTimeout": 60,
        "snmpVersion": "v2",
        "userName": "******"
    }

    add_data = dnac.devices.add_device(**payload)

    time.sleep(10)
    task = add_data["response"]["taskId"]
    task_data = dnac.task.get_task_by_id(task)

    if not task_data["response"]["isError"]:
        print("New device sucessfully added")
    else:
        print(f"Async task error seen: {task_data['progress']}")
Exemplo n.º 4
0
    def __init__(self, moddef, params, verbosity):
        self.params = params
        self.verbosity = verbosity
        self.result = dict(changed=False)
        self.validate_response_schema = self.params.get("validate_response_schema")
        self.api = api.DNACenterAPI(
            username=self.params.get("dnac_username"),
            password=self.params.get("dnac_password"),
            base_url="https://{}:{}".format(
                self.params.get("dnac_host"), self.params.get("dnac_port")
            ),
            version=self.params.get("dnac_version"),
            verify=self.params.get("dnac_verify"),
        )
        self.moddef = moddef
        self.params = self.moddef.strip_common_params(self.params)
        self.params = self.moddef.strip_unused_params(self.params)
        self.existing_object = {}

        if self.params.get("filename") and self.params.get("filepath"):
            filename = self.params.pop("filename")
            filepath = self.params.pop("filepath")
            self.params.setdefault(
                "multipart_fields", {"file": (filename, open(filepath, "rb"))}
            )
            self.params.setdefault("multipart_monitor_callback", None)
Exemplo n.º 5
0
def main():
    dnac = api.DNACenterAPI(base_url="https://sandboxdnac.cisco.com",
                            username="******",
                            password="******")

    devices = dnac.devices.get_device_list()

    for device in devices["response"]:
        print(f"ID: {device['id']} IP: {device['managementIpAddress']}")
def GetSwitchList():
    # Connecting to DNAC
    global dnac
    dnac = api.DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                            version=DNAC_VERSION,
                            verify=False)
    switches = dnac.devices.get_device_list(family='Switches and Hubs')
    return (switches['response'])
Exemplo n.º 7
0
def main():
    #  Create DNAC object
    dnac = api.DNACenterAPI(base_url="https://sandboxdnac2.cisco.com",
                            username='******',
                            password='******')

    devices = dnac.devices.get_device_list()

    for device in devices['response']:
        print(f"ID: {device['id']} IP: {device['managementIpAddress']}")
def CreateNetworkProfile(templateId):
    dnac = api.DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                            version=DNAC_VERSION,
                            verify=False)
    body = {
    "siteProfileUuid": "",
    "version": 0,
    "name": profile_name,
    "namespace": "switching",
    "profileAttributes": [
        {
            "key": "cli.templates",
            "attribs": [
                {
                    "key": "device.family",
                    "value": "Switches and Hubs",
                    "attribs": [
                        {
                            "key": "device.series",
                            "value": "",
                            "attribs": [
                                {
                                    "key": "device.type",
                                    "value": "",
                                    "attribs": [
                                        {
                                            "key": "template.id",
                                            "value": templateId,
                                            "attribs": [
                                                {
                                                    "key": "template.version",
                                                    "value": "1"
                                                },
                                                {
                                                    "key": "template.name",
                                                    "value": template_name
                                                }
                                            ]
                                        },
                                        {
                                            "key": "device.tag",
                                            "value": "",
                                            "attribs": []
        }]}]}]}]}]}
    taskId = dnacPost("api/v1/siteprofile", body).json()
    taskStatus = dnac.task.get_task_by_id(taskId['response']['taskId'])
    if taskStatus['response']['isError'] == True:
        raise Exception (" **** Network Profile Creation FAILED ****")
    profileStart = taskStatus['response']['progress'].find("[")
    profileStop  = taskStatus['response']['progress'].find("]")
    profileId = taskStatus['response']['progress'][profileStart+1:profileStop]
    return(profileId)
def CheckTemplate(projectId, templateX):
    # Connecting to DNAC
    global dnac
    dnac = api.DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                            version=DNAC_VERSION,
                            verify=False)
    templates = dnac.configuration_templates.gets_the_templates_available()
    for template in templates:
        if template['name'] == templateX:
            return (template['templateId'])
    return (CreateTemplate(projectId, templateX))
def CheckProject(projectX):
    # Connecting to DNAC
    global dnac
    dnac = api.DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                            version=DNAC_VERSION,
                            verify=False)
    projects = dnac.configuration_templates.get_projects()
    for project in projects:
        if project['name'] == projectX:
            return (project['id'])
    # If project does not exist:
    return (CreateProject(projectX))
Exemplo n.º 11
0
def main():

    if sys.argv[4] < "1.2":
        print(
            "Verification only supported for DNAC versions from 1.2.2 onward")
        return

    matrix = matrix_builder(sys.argv[4])
    # Retrieves token for DNAC API
    dnac = api.DNACenterAPI(username=sys.argv[1],
                            password=sys.argv[2],
                            base_url=sys.argv[3],
                            verify=False)
    verify_versions(dnac, matrix)
Exemplo n.º 12
0
def main():
    """
    Execution begins here.
    """

    # Create DNAC object, which automatically handles the token
    # request process. API docs in the link below, which may change:
    # https://dnacentersdk.readthedocs.io/en/latest/api/api.html
    dnac = api.DNACenterAPI(
        base_url="https://sandboxdnac.cisco.com",
        username="******",
        password="******",
    )

    # New device to add, same information as previous course
    new_device_dict = {
        "ipAddress": ["192.0.2.1"],
        "snmpVersion": "v2",
        "snmpROCommunity": "readonly",
        "snmpRWCommunity": "readwrite",
        "snmpRetry": 1,
        "snmpTimeout": 60,
        "cliTransport": "ssh",
        "userName": "******",
        "password": "******",
        "enablePassword": "******",
    }

    # Unpack the new device dictionary into keyword arguments (kwargs) and
    # pass into the SDK. This also performs data validation, so if we
    # have the wrong data or miss a required field, it tells us.
    add_data = dnac.devices.add_device(**new_device_dict)

    # Debugging line; pretty-print JSON to see structure
    # import json; print(json.dumps(add_data, indent=2))

    # Wait 10 seconds and get the async task ID
    time.sleep(10)
    task = add_data["response"]["taskId"]
    task_data = dnac.task.get_task_by_id(task)

    # Debugging line; pretty-print JSON to see structure
    # import json; print(json.dumps(task_data, indent=2))

    # Ensure async task completed successfully
    if not task_data["response"]["isError"]:
        print("New device successfully added")
    else:
        print(f"Async task error seen: {task_data['progress']}")
Exemplo n.º 13
0
def main():
    dna_center_access = api.DNACenterAPI(
        username="******",
        password="******",
        base_url="https://sandboxdnac.cisco.com/dna",
    )

    get_devices = dna_center_access.devices.get_device_list()
    for device_num, device in enumerate(get_devices['response']):
        device_type = device['type']
        device_ip = device['managementIpAddress']
        device_id = device['id']
        print(
            f"Device number {device_num+1} is type {device_type} and has ID of {device_id} and IP of {device_ip}"
        )
def AssociateProfileToAllSites(profileId):
    dnac = api.DNACenterAPI(username=DNAC_USER,
                        password=DNAC_PASSWORD,
                        base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                        version=DNAC_VERSION,
                        verify=False)
    sites = dnac.sites.get_site()['response']
    for site in sites:
        if site['name'] == "Global":
            break
    uri = f"api/v1/siteprofile/{profileId}/site/{site['id']}"
    taskId = dnacPost(uri, "").json()
    taskStatus = dnac.task.get_task_by_id(taskId['response']['taskId'])
    if taskStatus['response']['isError'] == True:
        raise Exception (" **** Network Profile Site Association FAILED ****")
    return(True)
def PortAssignment(deviceIp, interface, vlan):
    # Connecting to DNAC
    global dnac
    dnac = api.DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            base_url="https://" + DNAC + ":" + str(DNAC_PORT),
                            version=DNAC_VERSION,
                            verify=False)
    projectId = CheckProject(project_name)
    print(f"\t\033[1;37;40mProject Id: {projectId}\033[0m")
    templateId = CheckTemplate(projectId, template_name)
    print(f"\t\033[1;37;40mTemplate Id: {templateId}\033[0m")
    params = {'vlan': vlan, 'int': interface}
    print(f"\t\033[1;37;40mParameters: {params}\033[0m")
    deploymentId = DeployTemplate(templateId, deviceIp, params)
    print(f"\t\033[1;37;40mDeployment Id: {deploymentId}\033[0m")
    return (IsDeploymentSuccessful)
Exemplo n.º 16
0
def main():
    if True:
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s')
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        logger.debug("logging enabled")
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    dnac = api.DNACenterAPI(base_url='https://{}:443'.format(DNAC),
                            username=DNAC_USER,
                            password=DNAC_PASSWORD,
                            verify=False,
                            version="1.3.0")
    file_cache = FileCache(dnac, logger)
    dump_files(file_cache)
Exemplo n.º 17
0
 def auth(self, tenant):
     """
     Cisco DNA Center API Object
     """
     try:
         obj = api.DNACenterAPI(
             username=tenant.username,
             password=tenant.password,
             base_url="https://" + tenant.hostname,
             # version="2.1.2",  # TODO
             verify=bool(tenant.verify),
         )
         self.dnac_status[tenant.hostname] = "success"
         return True, obj
     except Exception as error_msg:
         print("Error for {}: {}".format(tenant, error_msg))
         self.dnac_status[tenant.hostname] = error_msg
         return False
 def __init__(self, params):
     self.result = dict(changed=False, result="")
     self.validate_response_schema = params.get("validate_response_schema")
     if DNAC_SDK_IS_INSTALLED:
         self.api = api.DNACenterAPI(
             username=params.get("dnac_username"),
             password=params.get("dnac_password"),
             base_url="https://{dnac_host}:{dnac_port}".format(
                 dnac_host=params.get("dnac_host"),
                 dnac_port=params.get("dnac_port")),
             version=params.get("dnac_version"),
             verify=params.get("dnac_verify"),
             debug=params.get("dnac_debug"),
         )
         if params.get("dnac_debug") and LOGGING_IN_STANDARD:
             logging.getLogger('dnacentersdk').addHandler(
                 logging.StreamHandler())
     else:
         self.fail_json(
             msg=
             "DNA Center Python SDK is not installed. Execute 'pip install dnacentersdk'"
         )
Exemplo n.º 19
0
from dnacentersdk import api
from requests.auth import HTTPBasicAuth

# Set Constants
SERVER = variables.DNAC_SERVER
USER = variables.DNAC_USER
PASSWORD = variables.DNAC_PASSWORD
VERSION = variables.DNAC_VERSION

# Disable warnings about untrusted certs
urllib3.disable_warnings()

# Create a global DNACenterAPI Connection Object to be used for subsequent API calls
dnac = api.DNACenterAPI(username=USER,
                        password=PASSWORD,
                        base_url=SERVER,
                        version=VERSION,
                        verify=False)


def get_auth_token():
    path = "/dna/system/api/v1/auth/token"
    url = SERVER + path
    hdr = {'content-type': 'application/json'}

    response = requests.post(url,
                             auth=HTTPBasicAuth(USER, PASSWORD),
                             headers=hdr,
                             verify=False).json()
    token = (response['Token'])
    return token
Exemplo n.º 20
0
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
"""

from dnacentersdk import api
import pprint
import requests.packages.urllib3
import config
from netmiko import ConnectHandler

requests.packages.urllib3.disable_warnings()

dnac = api.DNACenterAPI(username=config.username,
                        password=config.password,
                        base_url=config.base_url,
                        version='2.1.2',
                        verify=False,
                        single_request_timeout=99999,
                        debug=False)

aps = dnac.devices.get_device_list(family="Unified AP")
ap_ids = []

for ap in aps["response"]:
    ap_ids.append(ap["id"])

switches = dnac.devices.get_device_list(family="Switches and Hubs")
switch_ids = []

for switch in switches["response"]:
    if switch['type'].startswith("Cisco Catalyst"):
Exemplo n.º 21
0
import json
import requests
import time
import pprint
from dnacentersdk import api
from dnacentersdk.exceptions import ApiError

#Suppressing warning due to lack of certificate verificaton in https connection
requests.packages.urllib3.disable_warnings() 

#open cred file for dnac connection establishment
with open('cred.json') as json_file:
    data = json.load(json_file)

dnac = api.DNACenterAPI(base_url=data['dnacurl'],
username=data['username'],password=data['passwd'], verify=False)

def task_status(taskid=None):
    #this function is used to get task status, it returns the json response
    headers={"content-type" : "application/json", "__runsync" : "True"}
    url = 'dna/intent/api/v1/task/' + taskid
    try:
        response = dnac.custom_caller.call_api(method="GET", resource_path=url, headers=headers)
        #print(json.dumps(response, indent=2))
        return response
    except ApiError as e:
        print(e)

def get_mycredentials():
    #this function is used to retrieve global site device credential ids
    headers={"content-type" : "application/json", "__runsync" : "True"}
Exemplo n.º 22
0
urllib3.disable_warnings()
"""
Used to inport devices into DNA Center using the network discovery API.

Takes an IP address and a hostname as arguments to pass in to the sdk
to create the post request.
"""

ip = sys.argv[1]
ipList = f"{ip}-{ip}"
hostname = sys.argv[2]

# Add credentials to dnasdk
dnac = api.DNACenterAPI(
    base_url='https://Your-IP-Here:443',
    username='',
    password='',
    verify=False  # if needed
)

# Add device to DNAC
dnac_output = dnac.network_discovery.start_discovery(
    discoveryType="Range",
    globalCredentialIdList=[
        # Add global credential id's here
    ],
    preferredMgmtIPMethod="UseLoopBack",
    protocolOrder="ssh",
    retry=0,
    timeout=5,
    ipAddressList=ipList,
    name=hostname)
        if currentsha is None:
            print("adding NEW:", end='')
            t.upload(content)
        elif currentsha != newsha:
            print("updating:", end='')
            t.update(content)
        else:
            print("No update required")


if __name__ == "__main__":
    parser = ArgumentParser(description='Select options.')
    parser.add_argument('--dir',
                        type=str,
                        required=True,
                        help="directory to load configs from ")
    parser.add_argument('-v', action='store_true', help="verbose")
    args = parser.parse_args()

    if args.v:
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s')
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        logger.debug("logging enabled")

    dnac = api.DNACenterAPI()

    upload_templates(dnac, args.dir)
Exemplo n.º 24
0
from dnacentersdk import api
import urllib3
import time
import json
urllib3.disable_warnings()

dnac = api.DNACenterAPI(
    username="******",  # Example username="******",
    password="******",  # Example password="******",
    base_url=
    "<IP ADDRESS or FQDN>",  # Example base_url="https://sandboxdnac.cisco.com
    version='1.3.3',
    verify=False)

devices = dnac.devices.get_device_list(platform_id='C9500-40X')
device_ids = []
for device in devices.response:
    device_ids.append(device.id)

print(device_ids)
commands = ['show version', "show ip interface brief"]
command_runner = dnac.command_runner.run_read_only_commands_on_devices(
    commands=commands, deviceUuids=device_ids, timeout=0)

time.sleep(20)

task = dnac.task.get_task_by_id(command_runner.response.taskId)
progress_json = json.loads(task.response.progress)
print(progress_json)
file_id = progress_json['fileId']
print(file_id)
Exemplo n.º 25
0
from dnacentersdk import api
import json
import time
import calendar
from pprint import pprint

dna = api.DNACenterAPI(username="******",
                       password="******",
                       base_url="https://sandboxdnac2.cisco.com")

##### NETWORKS AND SITES ####

# Print Site Topology
sites = dna.networks.get_site_topology()
for site in sites.response.sites:
    for child_sites in sites.response.sites:
        if child_sites.parentId == site.id:
            print(f'{site.name} -> {child_sites.name}')
        for more_children in sites.response.sites:
            if more_children.parentId == child_sites.id and child_sites.parentId == site.id:
                print(
                    f'{site.name} -> {child_sites.name} -> {more_children.name}'
                )

# Print Vlans
vlans = dna.networks.get_vlan_details()
for vlan in vlans.response:
    print(vlan)

# Physical Topology Details
phys_top = dna.networks.get_physical_topology()
Exemplo n.º 26
0
import os

# There is an anomaly with how the SDK ingests environment variables.  It is done at the time of import of the sdk only.
# This means the credentials must already be defined in the environment and precludes the use of dotenv or similar
# techniques to programmatically configure the environment.
#
username = "******"
password = "******"
version = "1.3.0"
verify = False
base_url = "https://dna-3-dnac.campus.wwtatc.local:443"

dnac = api.DNACenterAPI(
    username=username,
    password=password,
    version=version,
    base_url=base_url,
    verify=verify,
)

# Create a sample site - note the use of additional header __runsync
# central = {
#     "type": "area",
#     "site": {
#         "area": {
#             "name": "Central",
#             "parentName": "Global"
#         }
#     }
# }
headers = {"__runsync": True}
Exemplo n.º 27
0
#!/usr/bin/env python
from __future__ import print_function
import time
import json
import requests
# turn off warninggs
requests.packages.urllib3.disable_warnings()
from dnac_config import DNAC, DNAC_USER, DNAC_PASSWORD

from dnacentersdk import api

dnac = api.DNACenterAPI(base_url='https://{}:443'.format(DNAC),
                                username=DNAC_USER,password=DNAC_PASSWORD,verify=False,version="1.3.0")

network_health= dnac.networks.get_overall_network_health(timestamp='')
#print (json.dumps(network_health,indent=2))

timestamp = int(time.time() * 1000)
client_health= dnac.clients.get_overall_client_health(timestamp='{}'.format(timestamp))
#print(json.dumps(client_health,indent=2))

result={}
for score in network_health.response:
    result["totalscore"] = score.healthScore
    result["totalcount"] = score.totalCount
for health in network_health.healthDistirubution:
    result[health.category+".score"] = health.healthScore
    result[health.category + ".count"] = health.count
for score in client_health.response[0].scoreDetail:
    result[score.scoreCategory.value+"-client.value"] = value=score.scoreValue
    result[score.scoreCategory.value+"-client.count"]= score.clientCount
    #print(uuids)
    ip_cache = {e[1]: e[0] for e in zip(ips, uuids)}
    #print(ip_cache)
    response = run_command(dnac, cmds, uuids)
    #print(json.dumps(response,indent=2))
    display(response, ip_cache)


if __name__ == "__main__":
    parser = ArgumentParser(description='Select options.')
    parser.add_argument('--commands',
                        type=str,
                        required=False,
                        help="command   ")

    parser.add_argument('-v', action='store_true', help="verbose")
    parser.add_argument('rest', nargs=REMAINDER)
    args = parser.parse_args()

    if args.v:
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s')
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        logger.debug("logging enabled")

    dnac = api.DNACenterAPI(version="1.3.0")

    all_run_command(dnac, args.commands.split(";"), args.rest)
Exemplo n.º 29
0
devicefamily = "Unified AP"

#
# specify what AP types you want to manipulate
#
aptypes = {'AIR-AP1815W-B-K9','C9105AXI-B'}

#
# info about your template
#
template="enablePorts"

#
# open connection to DNAC center
#
dnac = api.DNACenterAPI(base_url=DNAC, username=USER, password=PASS)

#
# get template info from DNAC and pull out the templateID
#
templates = (dnac.configuration_templates.gets_the_templates_available())
template_dict = list(filter(lambda x:x["name"]==template,templates))[0]
template_id = template_dict['templateId']

#
# get the devices
#
devices = dnac.devices.get_device_list(family=devicefamily)

count = 0
for device in devices.response:
Exemplo n.º 30
0
from dnacentersdk import api
import json
import time
import calendar

# time and calender for timestamp variable

dna = api.DNACenterAPI(base_url='https://sandboxdnac2.cisco.com',
                       username='******',
                       password='******')

##### NETWORKS AND SITES ####

# Print Site Topology
sites = dna.networks.get_site_topology()
for site in sites.response.sites:
    if site.parentId == 'a7cbac22-d82e-42ed-a705-b51829e955fa':
        print(site.name)
        for child_sites in sites.response.sites:
            if child_sites.parentId == site.id:
                print(f'  {child_sites.name}')
            for more_children in sites.response.sites:
                if more_children.parentId == child_sites.id and child_sites.parentId == site.id:
                    print(f'    {more_children.name}')
    print(' ')

# Print Vlans
vlans = dna.networks.get_vlan_details()
for vlan in vlans.response:
    print(vlan)