def get_tenants():
    token = get_token()

    base_url = f"https://10.48.109.8/api/v1/"
    tenant_url = "tenants"

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {token}"
    }

    overview_sites = {
        "5d84ee4a0e0000bc29476f2a": "netsol-fabric-1",
        "5e303ef41100007d3d586772": "netsol-fabric-2",
        "5f438740130000b2a2c206c8": "aws-eu",
        "5e53f86d1100009093586773": "bea-arch-fabric3",
        "5e53f8a31100009993586774": "bea-arch-fabric4"
    }

    response = requests.get(f"{base_url}{tenant_url}",
                            headers=headers,
                            verify=False).json()
    tenants = response["tenants"]

    for tenant in tenants:
        print(f"Tenant: {tenant['displayName']} -- {tenant['id']}")
        for site in tenant["siteAssociations"]:
            print(f"\t{overview_sites[site['siteId']]}")
示例#2
0
def main():
   #dnac = "sandboxdnac2.cisco.com"
   dnac = "10.48.82.183"

   token = get_token(dnac)

   url = f"https://{dnac}"

   site_name = "TESTSITE"
   building_name = "TESTBUILDING"
   floor_name = "TESTFLOOR-2"
   
   headers = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-auth-Token": token 
   }  

   # Read in the device configuration to be used in the payload of the REST request
   with open("templates/dummy_device.json", "r") as file:
      payload = json.load(file)

   # Add the device (https://{{dnac}}/dna/intent/api/v1/network-device)
   device_url = f"{url}/api/v1/network-device"
   response = requests.post(device_url, headers=headers, data=json.dumps(payload), verify=False ).json()
   print(response)
def main():
    #dnac = "sandboxdnac2.cisco.com"
    dnac = "10.48.82.183"

    token = get_token(dnac)

    url = f"https://{dnac}/dna/intent/api/v1/site"

    site_name = "TESTSITE"
    building_name = "TESTBUILDING"
    floor_name = "TESTFLOOR"

    jinja_templates = Environment(loader=FileSystemLoader('templates'),
                                  trim_blocks=True)
    template = jinja_templates.get_template("site_building_floor.j2.json")
    payload = template.render(site_name=site_name,
                              building_name=building_name,
                              floor_name=floor_name)

    print(payload)

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-auth-Token": token
    }

    response = requests.post(url, headers=headers, data=payload, verify=False)

    print(response)
def main():
   #dnac = "sandboxdnac2.cisco.com"
   dnac = "10.48.82.183"

   token = get_token(dnac)

   url = f"https://{dnac}"

   site_name = "TESTSITE"
   
   jinja_templates = Environment(loader=FileSystemLoader('templates'), trim_blocks=True)
   template = jinja_templates.get_template("site.j2.json")
   payload = template.render(site_name=site_name)

   headers = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-auth-Token": token 
   }  

   site_url = "/dna/intent/api/v1/site"
   response =  requests.post(url + site_url, headers=headers, data=payload, verify=False ).json()

   executionStatusUrl = response['executionStatusUrl']
   
   while True:
      response =  requests.get(url+executionStatusUrl, headers=headers, data=payload, verify=False ).json()
      if response['status'] == "SUCCESS":
         print("Site was successfully added")
         break
      else:
         print("Still in progress")
      time.sleep(1)
def main():
   #dnac = "sandboxdnac2.cisco.com"
   dnac = "10.48.82.183"

   token = get_token(dnac)


   url = f"https://{dnac}/dna/intent/api/v1/site"

   headers = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-auth-Token": token 
   }

   response =  requests.get(url, headers=headers, verify=False ).json()

   sites = response["response"]
   
   sitelist = []
   for site in sites:
      if 'parentId' in site.keys():
         sitelist.append(site['siteNameHierarchy'])
   
   #print(sitelist)

   sitelist.sort()
   for line in sitelist:
      print('   '*line.count('/') + line.split('/')[-1])
def main():
    dnac = "10.48.82.183"

    token = get_token(dnac)

    site_name = "TESTSITE"
    building_name = "TESTBUILDING"
    floor_name = "TESTFLOOR-2"

    url = f"https://{dnac}"

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-auth-Token": token
    }

    site_url = f"{url}/dna/intent/api/v1/site?name=Global/{site_name}"
    print(site_url)
    response = requests.get(site_url, headers=headers, verify=False).json()

    site_id = response['response'][0]['id']
    membership_url = f"{url}/dna/intent/api/v1/membership/{site_id}"
    print(membership_url)
    response = requests.get(membership_url, headers=headers,
                            verify=False).json()
    pprint(response)
def main():
    dnac = "sandboxdnac2.cisco.com"
    token = get_token(dnac)

    url = f"https://{dnac}/dna/intent/api/v1/client-health"

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-auth-Token": token
    }

    querystring = {"timestamp": ""}

    response = requests.get(url,
                            headers=headers,
                            params=querystring,
                            verify=False).json()

    scores = response['response'][0]['scoreDetail']

    d = {'wired': {}, 'wireless': {}}
    nested_dict_wired = {}
    nested_dict_wireless = {}

    # Walk over all scores and for each one (wired and wireless) determine the quality levels
    # and the amount of clients for each quality level. Ultimately, we will get this dict:

    # {
    # 'wired':
    #   {
    #     'POOR': 0, 'FAIR': 0, 'GOOD': 2, 'IDLE': 0, 'NODATA': 0, 'NEW': 0
    #   },
    #   'wireless':
    #   {
    #      'POOR': 0, 'FAIR': 42, 'GOOD': 22, 'IDLE': 0, 'NODATA': 0, 'NEW': 0
    #   }
    # }

    print("Overview")
    print("--------")
    for score in scores:

        if score['scoreCategory']['value'] == 'WIRED':
            values = score['scoreList']
            for value in values:
                nested_dict_wired[value['scoreCategory']
                                  ['value']] = value['clientCount']
                d['wired'] = nested_dict_wired

        if score['scoreCategory']['value'] == 'WIRELESS':
            values = score['scoreList']
            for value in values:
                nested_dict_wireless[value['scoreCategory']
                                     ['value']] = value['clientCount']
                d['wireless'] = nested_dict_wireless

    calculatePercentageHealth(d)
def main():
   #dnac = "sandboxdnac2.cisco.com"
   dnac = "10.48.82.183"

   token = get_token(dnac)

   url = f"https://{dnac}"

   site_name = "TESTSITE"
   building_name = "TESTBUILDING"
   floor_name = "TESTFLOOR-1"
   
   headers = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-auth-Token": token 
   }  

   # Read in the device configuration to be used in the payload of the REST request
   with open("templates/dummy_device.json", "r") as file:
      payload = json.load(file)

   # Add the device (https://{{dnac}}/dna/intent/api/v1/network-device)
   print("Adding the device")
   device_url = f"{url}/api/v1/network-device"
   response = requests.post(device_url, headers=headers, data=json.dumps(payload), verify=False ).json()
   deviceip = payload["ipAddress"][0]

   # Retrieve the ID of the floor with the provided name
   print("Retrieving the floor ID")
   floor_url = f"/dna/intent/api/v1/site?name=Global/{site_name}/{building_name}/{floor_name}"
   response_floor =  requests.get(url + floor_url, headers=headers, verify=False ).json()
   floor_id = response_floor['response'][0]['id']

   # Call the API to assign the device to the floor with ID floor_id
   print(f"Assign the device to the floor with id {floor_id}")
   site_url = f"{url}/dna/system/api/v1/site/{floor_id}/device" 
   payload = {"device": [{ "ip" : deviceip }]}
   
   response = requests.post(site_url, headers=headers, data=json.dumps(payload), verify=False ).json()
   
   #Check the execution status
   executionStatusUrl = response['executionStatusUrl']

   print("Checking the execution status")
   while True:
      response =  requests.get(url+executionStatusUrl, headers=headers, data=payload, verify=False ).json()
      if response['status'] == "SUCCESS":
         print("Device was successfully assigned")
         break
      else:
         print("Device assignment still in progress")
      time.sleep(1)
def main():
   #dnac = "sandboxdnac2.cisco.com"
   dnac = "10.48.82.183"

   token = get_token(dnac)

   url = f"https://{dnac}"

   site_name = "TESTSITE"
   building_name = "TESTBUILDING"
   floor_name = "TESTFLOOR-1"
   mydict = {}

   headers = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-auth-Token": token 
   }  

   floor_url = f"/dna/intent/api/v1/site?name=Global/{site_name}/{building_name}/{floor_name}"
   response_floor =  requests.get(url + floor_url, headers=headers, verify=False ).json()
   mydict['floor'] = response_floor['response'][0]['id']

   building_url = f"/dna/intent/api/v1/site?name=Global/{site_name}/{building_name}"
   response_building =  requests.get(url + building_url, headers=headers, verify=False ).json()
   mydict['building'] = response_building['response'][0]['id']

   site_url = f"/dna/intent/api/v1/site?name=Global/{site_name}"
   response_site =  requests.get(url + site_url, headers=headers, verify=False ).json()
   mydict['site'] = response_site['response'][0]['id']

   print(mydict)

   site_url = url + "/dna/intent/api/v1/site/"
   for k, v in mydict.items():
      print(f"Deleting {k}")
      response =  requests.delete(site_url + v, headers=headers, verify=False ).json()
      executionStatusUrl = response['executionStatusUrl']

      while True:
         response =  requests.get(url+executionStatusUrl, headers=headers, verify=False ).json()
         if response['status'] == "SUCCESS":
            print("Delete action was successfully")
            break
         else:
            print("Delete action still in progress")
         time.sleep(1)
示例#10
0
def main():
    dnac = "sandboxdnac2.cisco.com"

    token = get_token(dnac)

    url = f"https://{dnac}/dna/intent/api/v1/network-device"

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-auth-Token": token
    }

    response = requests.get(url, headers=headers, verify=False).json()
    devices = response["response"]

    for device in devices:
        if device['type'] is not None:
            print(
                f"{device['type']} with serial number {device['serialNumber']}"
            )
def get_devices():
    dnac = "sandboxdnac2.cisco.com"

    token = get_token(dnac)

    url = f"https://{dnac}/dna/intent/api/v1/network-device"

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-auth-Token": token
    }

    response = requests.get(url, headers=headers, verify=False).json()
    devices = response["response"]
    #print(devices)

    finaloutput = ""
    for device in devices:
        output = f"hostname: {device['hostname']}, serial: {device['serialNumber']}, platform: {device['serialNumber']}\n"
        finaloutput += output
        #print(output)
    send_message(finaloutput)
示例#12
0
def main():
    token = get_token()

    dnac = "sandboxdnac2.cisco.com"
    url = f"https://{dnac}/dna/intent/api/v1/"
    family = "Switches and Hubs"

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-auth-Token": token
    }

    device_url = url + "network-device?family=" + family
    response = requests.get(device_url, headers=headers, verify=False).json()
    devices = response["response"]

    device_list = []

    for device in devices:
        #print(f"{device['type']} with ID {device['id']}")
        device_list.append(device['id'])

    for device_id in device_list:
        print("Investigating device: " + device_id)
        new_interface_url = url + "interface/network-device/" + device_id
        #print(new_interface_url)
        response = requests.get(new_interface_url,
                                headers=headers,
                                verify=False).json()
        interfaces = response["response"]
        for interface in interfaces:
            if interface['ipv4Address'] is not None:
                print(
                    f"    {interface['portName']} with IP address {interface['ipv4Address']}"
                )
示例#13
0
        return

    type_rep, response = msg_parser.parse_message(message)

    # This is an invite request
    if type_rep == 0:
        invite = await client.create_invite(message.channel, max_age=15)
        await client.send_message(message.channel, invite)
        return

    # This is a messaege/file to be sent
    elif type_rep > 0 and response != '':
        if type_rep == RESPONSE_TYPE['MESSAGE']:
            await client.send_message(message.channel, response)
        elif type_rep == RESPONSE_TYPE['FILE']:
            await client.send_file(message.channel, response)


# Call after the bot is done connecting to Discord
@client.event
async def on_ready():
    """Function when start up."""
    print('Logged in as')
    print('USERNAME : %s' % client.user.name)
    print('USER ID : %s' % client.user.id)
    print('------')


# Start the bot
client.run(get_token())
示例#14
0
import requests
from authenticate import get_token
import json, time
from jinja2 import Environment
from jinja2 import FileSystemLoader

dnac = "10.48.82.183"
token = get_token(dnac)

url = f"https://{dnac}"

headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "X-auth-Token": token
}


def flowanalysis():
    payload = {
        "sourceIP": "192.168.30.60",
        "destIP": "192.168.13.64",
        "inclusions": ["INTERFACE-STATS", "DEVICE-STATS", "QOS-STATS"],
        "controlPath": False,
        "periodicRefresh": False
    }

    flow_url = "/dna/intent/api/v1/flow-analysis"
    print(url + flow_url)
    response_flow = requests.post(url + flow_url,
                                  data=json.dumps(payload),
示例#15
0
文件: app.py 项目: kumar-ish/Musicama
def get_token():
    global token
    token = authenticate.get_token(Musicama.USERNAME)
    return token
import requests
import json
from authenticate import get_token
import time, datetime
import os

url = 'https://api.spotify.com/v1/me/player'

#get a token
token = get_token()
print("getting token...")


def main():
    header = {'Authorization': 'Bearer ' + token}
    resp = requests.get(url=url, headers=header)
    data = json.loads(resp.text)

    device_name = (data['device'])['name']

    song_length = int((data['item'])['duration_ms'] / 1000)
    song_progress = int(data['progress_ms'] / 1000)
    song_percentage = int((song_progress / song_length) * 100)

    song_artist = data['item']['artists'][0]['name']
    song_name = (data['item'])['name']

    progress_24 = '#' * song_percentage + ('-' * (24 - song_percentage))

    print('Playing on: ' + device_name)
    print(song_artist)
示例#17
0
    try:
        with open(fName, 'w', encoding='utf-8-sig') as csvFile:
            writer = csv.DictWriter(csvFile, fieldnames=csvColumns)
            writer.writeheader()
            for row in listOfDict:
                writer.writerow(row)
    except IOError:
        print("I/O error")
    csvFile.close()
    return ()


if __name__ == "__main__":
    #authenticate to target DNAC and get token
    dnac_parameters = process_args(sys.argv)
    token = get_token(dnac_parameters)

    #get # of devices in DNAC
    device_count = getDeviceCount(dnac_parameters['host'])

    #get AP's and associated attributes
    ap_table = getAPList(dnac_parameters['host'], device_count)

    #get physical topology
    topology = getPhysicalTopology(dnac_parameters['host'])

    #add merge cdp neighbor information with ap_table
    ap_report = merge_topology(ap_table, topology)

    #output report
    report_name = 'ap_neighbor_report.csv'