def test_get_enviroment_after_import_2(monkeypatch, reset_env_vars,
                                       import_fixture):
    """Tests if the package gets the values of the env variables after import."""
    from dnacentersdk import DNACenterAPI
    monkeypatch.setenv("DNA_CENTER_ENCODED_AUTH", import_fixture.encoded_auth)
    monkeypatch.setenv("DNA_CENTER_BASE_URL", import_fixture.base_url)
    DNACenterAPI(verify=import_fixture.verify, debug=import_fixture.debug)
    return True
def test_get_enviroment_exception_3(monkeypatch, reset_env_vars,
                                    import_fixture):
    """Remove the SECRET env vars and assert AccessTokenError is raised."""
    # missing encoded_auth or (username and password)
    monkeypatch.setenv("DNA_CENTER_BASE_URL", import_fixture.base_url)
    from dnacentersdk import DNACenterAPI, AccessTokenError
    with pytest.raises(AccessTokenError):
        DNACenterAPI(verify=import_fixture.verify, debug=import_fixture.debug)
def test_get_enviroment_after_import_1(monkeypatch, reset_env_vars,
                                       import_fixture):
    """Tests if the package gets the values of the env variables after import."""
    from dnacentersdk import DNACenterAPI
    monkeypatch.setenv("DNA_CENTER_USERNAME", import_fixture.username)
    monkeypatch.setenv("DNA_CENTER_PASSWORD", import_fixture.password)
    monkeypatch.setenv("DNA_CENTER_BASE_URL", import_fixture.base_url)
    DNACenterAPI(verify=import_fixture.verify, debug=import_fixture.debug)
    return True
Beispiel #4
0
def api(mock_dnac_server, base_url):
    return DNACenterAPI(username=DNA_CENTER_USERNAME,
                        password=DNA_CENTER_PASSWORD,
                        encoded_auth=DNA_CENTER_ENCODED_AUTH,
                        base_url=base_url,
                        single_request_timeout=DEFAULT_SINGLE_REQUEST_TIMEOUT,
                        wait_on_rate_limit=DEFAULT_WAIT_ON_RATE_LIMIT,
                        verify=DEFAULT_VERIFY,
                        version=DNA_CENTER_VERSION)
Beispiel #5
0
def get_dnac_token(env_creds):
    """
    This function will Authenticate against Cisco DNA Center server and print out a list of all managed devices
    """
    dnac = DNACenterAPI(username=env_creds['data']['username'],
                        password=env_creds['data']['password'],
                        base_url=env_creds['data']['url'])
    print("DNAC API Authenticated ...")
    print("Gathering Device Info ... \n")
    devices = dnac.devices.get_device_list()
    for device in devices.response:
        print("Device Management IP {} for {} ".format(
            device.managementIpAddress, device.hostname))
Beispiel #6
0
def sdk_setup_dnacentersdk(api_creds):
    try:
        username = api_creds['dnacentersdk']['username']
        password = api_creds['dnacentersdk']['password']
        base_url = api_creds['dnacentersdk']['base_url']
        version = api_creds['dnacentersdk']['api_version']
        verify = str(api_creds['dnacentersdk']['verify']).lower() in ['true']
        api = DNACenterAPI(base_url=base_url, version=version, username=username, password=password, verify=verify)
        logger.info('API connectivity established with dnacentersdk')
        return api
    except Exception as e:
        logger.error('error connecting to dnacentersdk.  Please verify connectivity, username and password')
        logger.error(e)
        exit()
Beispiel #7
0
def main():
    print('**DNA Center client to be monitored: **', CLIENT_MAC)

    # alerts will be send until the alert counter reaches the max alert count
    alert_count = 0

    while alert_count < MAX_ALERT:

        alert = False

        dna_center = DNACenterAPI(username=DNAC_USER,
                                  password=DNAC_PASS,
                                  base_url=DNAC_URL,
                                  verify=False)
        client_info = dna_center.clients.get_client_detail(
            mac_address=CLIENT_MAC)

        # parse the client health score, ap name, snr, location
        try:
            health_score = client_info['detail']['healthScore']
            for score in health_score:
                if score['healthType'] == 'OVERALL':
                    client_health = score['score']
            ap_name = client_info['detail']['clientConnection']
            snr = float(client_info['detail']['snr'])
            location = client_info['detail']['location']
        except:
            print('**client not in DNA Center**')

        alert = client_health_check(alert, client_health)

        if alert:
            print("**sending bot message**")

            message = f"DNA Center VIP Client Alert:\n" \
                      f" Please review the information for the VIP Client-{CLIENT_MAC}:\n" \
                      f"Location: {location}\n" \
                      f"AP: {ap_name}\n" \
                      f"Health: {client_health}\n" \
                      f"SNR: {snr}"

            # send message from slack bot to the specified space: #bot-project
            send_slack_message('#bot-project', message)

            alert_count += 1
            time.sleep(5)
Beispiel #8
0
def main(ctx, username, password, encoded_auth, base_url, version,
         single_request_timeout, wait_on_rate_limit, verify, debug, prompt):
    """DNA Center API wrapper.

    DNACenterAPI wraps all of the individual DNA Center APIs and represents
    them in a simple hierarchical structure.

    """

    if prompt:
        username = click.prompt('Username',
                                default=username,
                                show_default=True)
        password_prompt = 'Password [****]' if password else 'Password'
        password = click.prompt(password_prompt,
                                default=password,
                                show_default=False,
                                hide_input=True,
                                confirmation_prompt='Repeat for confirmation')

    urllib3.disable_warnings()
    spinner = init_spinner(beep=False)
    start_spinner(spinner)
    try:
        ctx.obj = DNACenterAPI(username,
                               password,
                               encoded_auth,
                               base_url=base_url,
                               single_request_timeout=single_request_timeout,
                               wait_on_rate_limit=wait_on_rate_limit,
                               verify=verify,
                               version=version,
                               debug=debug)
        stop_spinner(spinner)
    except Exception as e:
        stop_spinner(spinner)
        tbprint()
        eprint('''Try "dnacentercli --help" for help.''')
        eprint('Error:', e)
        ctx.exit(-1)
Beispiel #9
0
def main():
    try:
        api = DNACenterAPI(username=username,
                           password=password,
                           base_url=base_url,
                           verify=False)  # This handles gather the token

        get_discovery = api.clients.get_overall_client_health(
        )  # Getting overall client health
        client_count = get_discovery['response'][0]['scoreDetail'][0][
            'clientUniqueCount']  # parsing down to get global client count

        print(f"\nthe global client count is: {client_count}"
              )  # printing client count

        get_site = api.sites.get_site_count(
        )  # getting number of sites created
        print(f"The number of sites are: {get_site['response']}"
              )  # printing number of sites.

    except ApiError as e:
        print(e)
Beispiel #10
0
            name = param.parameterName
            params.append({"key": name, "value": self.__dict__[name]})
        return params

if __name__ == '__main__':

    with open('pnp_params.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)

        devices = []
        for device in reader:
            devices.append(Device(device))

    api = DNACenterAPI(username=dnac_credentials.username,
                       password=dnac_credentials.password,
                       base_url=dnac_credentials.url,
                       version='2.1.2',
                       verify=False)

    for device in devices:

        device.get_site_id(api)
        device.get_stack()
        device.get_template_id(api)
        device.get_image_id(api)
        variables = device.get_params(api)

        # Add Device
        device_add_payload = [{
            "deviceInfo": {
                "hostname": device.name,
Beispiel #11
0
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')


api = DNACenterAPI(verify=False, debug=True)

logging.getLogger('dnacentersdk').addHandler(logging.StreamHandler())
# logging.getLogger('dnacentersdk').addHandler(ch)

api.devices.get_device_list()

# CONFIGURE logger correctly following
# https://docs.python.org/3.7/howto/logging.html#configuring-logging
# We were using basic logging
# if we remove the line debug does not log
Beispiel #12
0
#! /usr/bin/env python3
from dnacentersdk import DNACenterAPI

# Create a DNACenterAPI connection object
# Pass arguments of username and password
myapi = DNACenterAPI(username="******", password="******", \
    base_url="https://sandboxdnac2.cisco.com")

# Get list of all devices
devices = myapi.devices.get_device_list()

# Print table 1 headers
print("="*96)
print("{0:25s}{1:1s}{2:46s}{3:1s}{4:23s}".\
    format("Device Name", "|", "Device Type", "|","Up Time"))
print("-"*96)

# Print table 1 content
for device in devices.response:
    print("{0:25s}{1:1s}{2:46s}{3:1s}{4:23s}".\
        format(device.hostname, "|", device.type, "|", device.upTime))
print("="*96)

# Get health of all clients on Thursday 21st January 2021, 2:27:00 PM ACT Adelaide
# Pass args of timestamp in UNIX epoch milliseconds
clients = myapi.clients.get_overall_client_health(timestamp="1611201420000")

# Print table 2 headers
print("{0:25s}{1:1s}{2:46s}{3:1s}{4:23s}".\
    format("Client Category", "|", "Number of Clients", "|","Clients Score"))
print("-"*96)
Beispiel #13
0
    workflow_db = tables.load_xl_db('dna_workflow_db.xlsx')

# Setup logging
if args.debug:
    level = logging.getLevelName('DEBUG')
else:
    level = logging.getLevelName('INFO')

logger = logging.getLogger('main')
logger.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.propagate = False

username = workflow_db['workflows']['api_creds'][0]['username']
password = workflow_db['workflows']['api_creds'][0]['password']
base_url = workflow_db['workflows']['api_creds'][0]['base_url']
version = workflow_db['workflows']['api_creds'][0]['api_version']
verify = workflow_db['workflows']['api_creds'][0]['verify']

if args.offline:
    api = None
else:
    api = DNACenterAPI(base_url=base_url, version=version, username=username, password=password, verify=verify)


if __name__ == "__main__":
    main()
Beispiel #14
0
import urllib3


class Device:
    def __init__(self, hostname, ipAddress, dictionary):
        self.hostname = hostname
        self.ipAddress = ipAddress
        self.add_device_status = None
        self.site_id = None
        for k, v in dictionary.items():
            setattr(self, k, v)


urllib3.disable_warnings()

api = DNACenterAPI()

app = Flask(__name__)


@app.route("/", methods=["POST", "GET"])
def home():
    if request.method == "POST":

        parameters = {
            'userName': request.form["userName"],
            'password': request.form["password"],
            'enablePassword': request.form["enablePassword"],
            'cliTransport': request.form["cliTransport"],
            'type': 'NETWORK_DEVICE',
            'snmpVersion': 'v2',
Beispiel #15
0
from env import config
from dnacentersdk import DNACenterAPI
import json

dnac = DNACenterAPI(username=config['DNAC_USER'],
                    password=config['DNAC_PASSWORD'],
                    base_url=config['DNAC_BASE_URL'],
                    version='2.1.2',
                    verify=True)

if __name__ == "__main__":
    inventory = dnac.devices.get_device_list().response
    relevant_inventory = []

    for device in inventory:
        relevant_device = {}

        relevant_device['mac'] = device['macAddress']
        relevant_device['serial'] = device['serialNumber']
        relevant_device['name'] = device['hostname']
        relevant_device['model'] = device['platformId']
        relevant_device['category'] = 'dnac'

        relevant_inventory.append(relevant_device)

    # Appends the existing Meraki inventory with DNAC inventory in inventory.json
    with open('inventory.json', 'r+') as output_file:
        # Ensures the json dump further on is appended at the end of the file
        existing_inventory = json.load(output_file)

        json.dump(relevant_inventory, output_file)
Beispiel #16
0
def main():
    """
    This application will monitor a wireless user client device.
    It will identify when the client experiences poor performance:
     - decreased total transmit and receive data
     - lower client health score
     - low SNR value
    If any of the above conditions are true, exceeding a predefined number of consecutive polling intervals,
    it will create a notification to Webex Teams
    """

    # logging, debug level, to file {application_run.log}
    logging.basicConfig(
        filename='application_run.log',
        level=logging.DEBUG,
        format=
        '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    current_time = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print('\nWireless Client Monitoring App Start, ', current_time)

    print('\nWireless client user to be monitored: ', CLIENT_USERNAME)

    # Create a DNACenterAPI "Connection Object"
    dnac_api = DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASS,
                            base_url=DNAC_URL,
                            version='2.1.2',
                            verify=False)

    # If client MAC Address not found, continue with pre-configured MAC Address

    all_client_info = dnac_api.clients.get_client_enrichment_details(
        headers={
            'entity_type': 'network_user_id',
            'entity_value': CLIENT_USERNAME
        })
    client_mac = ''
    if all_client_info != []:
        for client in all_client_info:
            if client['userDetails']['hostType'] == 'WIRELESS':
                client_mac = client['userDetails']['id']
    else:
        print(
            '\nUnknown wireless client MAC Address for the client with the username: '******'':
        print(
            'Wireless client MAC address not found, use the pre-configured MAC Address: ',
            CLIENT_MAC)
        client_mac = CLIENT_MAC
    else:
        print('\nWireless Client MAC Address found: ', client_mac, '\n')

    # start to collect data about the monitored client
    # poll the client until notification will be sent ot Webex

    alert_count = 0  # used to count when minimum performance params are not met

    while alert_count < COUNTER_MAX:

        # initialize the alert flag, used to identify if any conditions of client poor performance are met
        alert = False

        # create a DNACenterAPI "Connection Object", to avoid token expiration after 60 minutes
        dnac_api = DNACenterAPI(username=DNAC_USER,
                                password=DNAC_PASS,
                                base_url=DNAC_URL,
                                version='2.1.2',
                                verify=False)

        # find out the epoch time msec
        timestamp = get_epoch_time()

        # receive the client detail info for the client with the MAC address at a specific timestamp
        client_info = dnac_api.clients.get_client_detail(
            mac_address=client_mac, timestamp=timestamp)

        # parse the total data transfer, ap name, snr, data rate, location, ssid
        try:
            health_score = client_info['detail']['healthScore']
            for score in health_score:
                if score['healthType'] == 'OVERALL':
                    client_health = score['score']
            total_data_transfer = float(
                client_info['detail']['txBytes']) + float(
                    client_info['detail']['rxBytes'])
            ap_name = client_info['detail']['clientConnection']
            snr = float(client_info['detail']['snr'])
            data_rate = float(client_info['detail']['dataRate'])
            location = client_info['detail']['location']
            ssid = client_info['detail']['ssid']
            print(client_health, total_data_transfer, data_rate, snr, ssid,
                  ap_name, location)
        except:
            print(
                '\nUnable to collect the client info, client not in the Cisco DNA Center inventory'
            )

        # verify client connectivity performance
        if client_health <= HEALTH_LOW:
            alert = True
        if snr <= SNR:
            alert = True
        if total_data_transfer <= BW_LOW:
            alert = True

        # if any of the above conditions are true, increase the alert_count
        # if performance improved during this poll interval, reset the alert_count
        if alert:
            alert_count += 1
        else:
            alert_count = 0
        print('Alert: ', alert, alert_count)

        # send the client data to the webhook receiver, to enable the bot functionality
        # prepare the payload
        current_time = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        client_report = {
            'username': CLIENT_USERNAME,
            'details': {
                'mac_address': client_mac,
                'location': location,
                'access_point': ap_name,
                'ssid': ssid,
                'health_score': health_score,
                'total_data': total_data_transfer,
                'snr': snr,
                'timestamp': current_time
            }
        }
        response = send_client_details(client_report, WEBHOOK_RECEIVER_URL,
                                       WEBHOOK_HEADER)
        print('\nWireless Client POST API status: ', response[1])

        time.sleep(TIME_INTERVAL * 60)

    # send notifications to Webex Teams

    # find the Webex Teams space id
    space_id = get_room_id(WHATSOP_ROOM)

    card_message = {
        "roomId":
        space_id,
        "markdown":
        "Wireless Client Notification",
        "attachments": [{
            "contentType": "application/vnd.microsoft.card.adaptive",
            "content": {
                "$schema":
                "http://adaptivecards.io/schemas/adaptive-card.json",
                "type":
                "AdaptiveCard",
                "version":
                "1.0",
                "body": [{
                    "type": "TextBlock",
                    "text": "Wireless Client Notification",
                    "weight": "bolder",
                    "size": "large"
                }, {
                    "type": "TextBlock",
                    "text":
                    "Cisco DNA Center identified low wireless performance for this client:",
                    "wrap": True
                }, {
                    "type":
                    "FactSet",
                    "facts": [{
                        "title": "Username: "******"value": CLIENT_USERNAME
                    }, {
                        "title": "MAC Address:",
                        "value": client_mac
                    }, {
                        "title": "Location:",
                        "value": location
                    }, {
                        "title": "Access Point:",
                        "value": ap_name
                    }, {
                        "title": "SSID:",
                        "value": ssid
                    }, {
                        "title": "Health Score:",
                        "value": str(client_health)
                    }, {
                        "title": "Total data:",
                        "value": str(total_data_transfer)
                    }, {
                        "title": "SNR:",
                        "value": str(snr)
                    }]
                }],
                "actions": [
                    {
                        "type":
                        "Action.openURL",
                        "title":
                        "Cisco DNA Center Client 360",
                        "url":
                        DNAC_URL +
                        '/dna/assurance/client/details?macAddress=' +
                        client_mac
                    }
                    # {
                    #    "type": "Action.openURL",
                    #    "title": "ServiceNow incident " + issue_number,
                    #    "url": jira_issue_url
                    # }
                ]
            }
        }]
    }

    post_room_card_message(card_message)

    print('Webex Teams notification message posted')

    current_time = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print('\nWireless Client Monitoring App Run End, ', current_time)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

which_dnac = "devnet"
devnet = {
    "debug": False,
    "username": "******",
    "password": "******",
    "base_url": "https://sandboxdnac2.cisco.com:443",
    "public_cert": False,
    "version": "1.3.0",
}
if which_dnac == "devnet":
    api = DNACenterAPI(
        username=devnet["username"],
        password=devnet["password"],
        base_url=devnet["base_url"],
        verify=devnet["public_cert"],
        debug=devnet["debug"],
        version=devnet["version"],
    )
else:
    print("No DNA Center connection information provided.  Exiting.")
    exit(0)

results = {}

print(api.devices.get_device_list())  # Permissions issue

results["workflows"] = api.pnp.get_workflows()
results["client_health"] = api.clients.get_overall_client_health()
results["all_device_configs"] = api.devices.get_device_config_for_all_devices()
def main():
    """
    This application will identify all Cisco DNA Center devices that are in one of these 'un-x' states:
    - un-claimed in the PnP inventory
    - un-assigned to a site
    - un-reachable by Cisco DNA Center
    It will create a report with the hostname and platform Id for these devices
    """

    # logging, debug level, to file {application_run.log}
    logging.basicConfig(
        filename='application_run.log',
        level=logging.DEBUG,
        format=
        '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    current_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print('\n"un-x_devices_report.py" App Run Start, ', current_time)

    # Create a DNACenterAPI "Connection Object"
    dnac_api = DNACenterAPI(username=DNAC_USER,
                            password=DNAC_PASS,
                            base_url=DNAC_URL,
                            version='2.1.2',
                            verify=False)

    # find all devices that are unclaimed in the PnP inventory
    devices_unclaimed = []
    devices_unclaimed_info = dnac_api.device_onboarding_pnp.get_device_list(
        state='Unclaimed')

    if devices_unclaimed_info == []:
        print('\nNo unclaimed devices found')
    else:
        for device in devices_unclaimed_info:
            devices_unclaimed.append({
                'hostname':
                device['deviceInfo']['hostname'],
                'pid':
                device['deviceInfo']['pid']
            })
        print('\n\nUnclaimed devices found:')
        print('{0:30} {1:30}'.format('Device Hostname', 'Device PID'))
        for device in devices_unclaimed:
            print('{0:30} {1:30}'.format(device['hostname'], device['pid']))

    # find all devices that are unreachable
    devices_unreachable = []
    devices_unreachable_info = dnac_api.devices.get_device_list(
        reachability_status='Unreachable')
    devices_unreachable_json = devices_unreachable_info['response']

    if devices_unreachable_json == []:
        print('\nNo unreachable devices found')
    else:
        for device in devices_unreachable_json:
            devices_unreachable.append({
                'hostname': device['hostname'],
                'pid': device['platformId']
            })
        print('\n\nUnreachable devices found:')
        print('{0:30} {1:30}'.format('Device Hostname', 'Device PID'))
        for device in devices_unreachable:
            print('{0:30} {1:30}'.format(device['hostname'], device['pid']))

    # find all devices that are unassigned to a site
    # we will find this information from the site membership API using the {Global} site id
    global_site_info = dnac_api.sites.get_site(name='Global')
    global_site_id = global_site_info['response'][0]['id']

    site_membership_info = dnac_api.sites.get_membership(
        site_id=global_site_id)

    devices_unassigned = []
    devices_unassigned_info = site_membership_info['device'][0]['response']

    if devices_unassigned_info == []:
        print('\nNo unassigned devices found')
    else:
        for device in devices_unassigned_info:
            devices_unassigned.append({
                'hostname': device['hostname'],
                'pid': device['platformId']
            })
        print('\n\nUnassigned devices found:')
        print('{0:30} {1:30}'.format('Device Hostname', 'Device PID'))
        for device in devices_unassigned:
            print('{0:30} {1:30}'.format(device['hostname'], device['pid']))

    current_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print('\n"un-x_devices_report.py" App Run End, ', current_time)
from dnacentersdk import DNACenterAPI  # import DNACenterAPI class

# Instantiate DNACenterAPI class passing in URL and credentials
# Does token handling for us
dna = DNACenterAPI(base_url='https://sandboxdnac2.cisco.com',
                   username='******',
                   password='******')
############### DEVICES #############
# Invoke method from devices class to get the list of devices
devices = dna.devices.get_device_list()
# Loop through the list of devices and print their details
for device in devices.response:
    print(device.type)
    print(device.hostname)
    print(device.managementIpAddress)
    print(device.id)
    print(" ")

# Get a specific device referencing it's unique ID
device = dna.devices.get_device_by_id('75d57d36-dade-40cb-aac3-b2267e7e0180')
print(device.response)
#!/usr/bin/env python

import requests
from dnacentersdk import DNACenterAPI
from pprint import pprint

dnac_url = "https://sandboxdnac2.cisco.com"
dnac_username = "******"
dnac_password = "******"

if (__name__ == "__main__"):
    dnac = DNACenterAPI(username=dnac_username, password=dnac_password, base_url=dnac_url)

    dnac_devices = dnac.devices.get_device_list()
    headers = ["Hostname","IP","Family"]
    header_format = "{:<25}{:<15}{:<15}"
    print(header_format.format(*headers))

    for dnac_device in dnac_devices['response']:
        dnac_device_details = [
            dnac_device['hostname'] or "N/A",
            dnac_device['managementIpAddress'] or "N/A",
            dnac_device['family'] or "N/A"
        ]

        print(header_format.format(*dnac_device_details))
Beispiel #21
0
from pprint import pprint

from dnacentersdk import DNACenterAPI

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

client_health = api.clients.get_overall_client_health()
pprint(client_health)


for site in client_health['response']:
    print('*' * 30)
    print("Site ID: {}".format(site['siteId']))
    print('*' * 30)

    for scoreType in site['scoreDetail']:
        client_category = scoreType['scoreCategory']['value']
        client_count = scoreType['clientCount']

        print("{} Clients: {}".format(client_category, client_count))

        if 'scoreList' in scoreType:
            for score_state in scoreType['scoreList']:
                score_state_category = score_state['scoreCategory']['value']
                score_state_client_count = score_state['clientCount']
                print("{:>10} Clients: {}".format(score_state_category, score_state_client_count))
def main(argv):
    try:
        # set default values for command line arguments
        initlogging(argv)
        global username
        global password
        global HOST
        myAction = CheckUsage(argv)
        while not myAction:
            newAction = input('Please choose option: ')
            myArgv = [argv, newAction]
            myAction = CheckUsage(myArgv)

        csv_file1 = None
        myTokenSuccess = False
        while not myTokenSuccess:
            try:
                import login
                if hasattr(login, 'username'):
                    username = login.username
                if hasattr(login, 'password'):
                    password = login.password
                if hasattr(login, 'HOST'):
                    HOST = login.HOST
                if username == '':
                    username = input('Enter your DNAC username: '******'':
                    password = getpass('Enter your DNAC password: '******'':
                    HOST = input("Please enter the DNAC's IP address: ")
            except ImportError:
                username = input('Enter your DNAC username: '******'Enter your DNAC password: '******'s IP address: ")
            #using DNAC API to retrieve token
            #TOKEN = getAuthToken(username, password)
            i = 0
            try:
                dnac_api = DNACenterAPI(username=username,
                                        password=password,
                                        base_url=f'https://{HOST}',
                                        verify=False)
                myTokenSuccess = True
            except ApiError as myErr:
                print(myErr)
            TOKEN = dnac_api.access_token
        if myArgv[1].lower() == 'importpoolsfromcsv':
            IpPoolsList = []
            with open(argv[2], 'r') as mycsv_file:
                myfieldnames = [
                    'Pool Name', 'Subnet', 'Site Name', 'Global Pool Name',
                    'DHCP Server IPs', 'DNS Server IPs', 'Default Gateway'
                ]
                myreader = csv.DictReader(mycsv_file, myfieldnames)
                for row in myreader:
                    if i == 0:
                        mylogger('Skipping row 1')
                        i = i + 1
                    else:
                        IpPoolsList.append(row)
                        #mylogger(row)

            SiteName = ''
            GlobalPoolName = ''
            SiteId = ''
            GlobalPoolId = ''
            for pool in IpPoolsList:
                mylogger(f'Begin processing site: {pool["Site Name"]}')
                if not SiteName == pool['Site Name'] or SiteId == '':
                    SiteName = pool['Site Name']
                    SiteId = getSiteId(pool['Site Name'], TOKEN)
                if not GlobalPoolName == pool[
                        'Global Pool Name'] or GlobalPoolId == '':
                    GlobalPoolName = pool['Global Pool Name']
                    GlobalPoolId = getGlobalPoolId(pool['Global Pool Name'],
                                                   TOKEN)
                PAYLOAD = {
                    "groupName":
                    pool["Pool Name"],
                    "groupOwner":
                    "DNAC",
                    "type":
                    "generic",
                    "siteId":
                    SiteId,
                    "ipPools": [{
                        "parentUuid": GlobalPoolId,
                        "dhcpServerIps": [pool["DHCP Server IPs"]],
                        "dnsServerIps": [pool["DNS Server IPs"]],
                        "ipPoolOwner": "DNAC",
                        "shared": True,
                        "gateways": [pool["Default Gateway"]],
                        "ipPoolCidr": pool["Subnet"]
                    }]
                }
                ReserveLocalPool(PAYLOAD, TOKEN)
        elif myArgv[1].lower() == 'createglobalpool':
            createglobalpool(dnac_api)

        elif myArgv[1].lower() == 'createdevicecredentials':
            createdevicecredentials(dnac_api)

        elif myArgv[1].lower() == 'createnetworksettings':
            pass

        elif myArgv[1].lower() == 'importfromexcel':
            filename = input('Excel file name (xlsx): ')
            import openpyxl as xl
            mywb = xl.load_workbook(filename)

            for sheet in mywb.sheetnames:
                if sheet == 'Sites':
                    ImportSites(mywb[sheet], dnac_api)
                #elif sheet == 'Pools':
                #    ImportPools(mywb[sheet], dnac_api)
                #elif sheet == 'Credentials':
                #    ImportCredentials(mywb[sheet], dnac_api)

        elif myArgv[1].lower() == 'deletefromexcel':
            filename = input('Excel file name (xlsx): ')
            import openpyxl as xl
            mywb = xl.load_workbook(filename)

            for sheet in mywb.sheetnames:
                if sheet == 'Sites':
                    DeleteSitesFromSheet(mywb[sheet], dnac_api)

        print(f'Base file name of logger is: {logfile}')
    except KeyboardInterrupt:
        print(f'Exception: base file name of logger is: {logfile}')
"""
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
               https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
"""

__author__ = "Kareem Iskander, DevNet Developer Advocate"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2020 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"

from dnacentersdk import DNACenterAPI

dnac_creds = {}
dnac_creds['url'] = 'https://sandboxdnac2.cisco.com'
dnac_creds['username'] = '******'
dnac_creds['password'] = '******'

if __name__ == '__main__':
    dnac = DNACenterAPI(username=dnac_creds['username'],
                        password=dnac_creds['password'],
                        base_url=dnac_creds['url'])
    print("Auth Token: ", dnac.access_token)
Beispiel #24
0
from dnacentersdk import DNACenterAPI
from dotenv import load_dotenv
from tabulate import tabulate
from pprint import pprint
from operator import itemgetter

dnac = DNACenterAPI(
    base_url="https://sandboxdnac2.cisco.com:443",
    version="1.3.0",
    username="******",
    password="******",
    verify=False
)

# Retrieve all Sites
# sites = dnac.sites.get_site()

# site_header = ["Name","Site Hierarchy"]

# site_data =[[site['name'],site['siteNameHierarchy']] for site in sites.response]

# for site in sites.response:
#     site_data.append([site['name'],site['siteNameHierarchy']])

# print(
#     tabulate(
#         sorted(
#             site_data, key=itemgetter(0)
#             ),
#         headers=site_header, tablefmt="fancy_grid"))