Exemplo n.º 1
0
def get_all_devices(organization_id=None, network_id=None) -> list:
    """Get all devices.

    Returns:
        Optional[dict]: Devices list
    """

    passFilter = False if organization_id is not None else True
    avai_devices = []
    client = MerakiSdkClient(config.MERAKI_AUTH_TOKEN)
    orgs = client.organizations.get_organizations()
    avai_orga = [
        {
            'organization_id': orgs[x]
        } for x in orgs
        if (not passFilter and orgs[x] == organization_id) or passFilter
    ]
    networks = client.networks.get_organization_networks(avai_orga)
    if networks:
        for network in networks:
            if network_id:
                if network['id'] == network_id:
                    avai_devices.append(
                        client.devices.get_network_devices(network['id']))
            else:
                avai_devices.append(
                    client.devices.get_network_devices(network['id']))

    return avai_devices
Exemplo n.º 2
0
def get_camera_network(camera_serial: str) -> dict:
    """Get network associated to camera.

    Args:
        camera_serial (str): Camera serial

    Returns:
        str: Network informations
    """
    client = MerakiSdkClient(config.MERAKI_AUTH_TOKEN)
    try:
        orgs = client.organizations.get_organizations()
        all_organizations = {}

        for org in orgs:
            all_organizations['organization_id'] = org['id']

        if all_organizations:  # make sure it's not an empty collection
            networks = client.networks.get_organization_networks(
                all_organizations)
            if networks:
                for network in networks:
                    devices = client.devices.get_network_devices(network['id'])
                    for device in devices:
                        if device['serial'] == camera_serial:
                            return network

    except Exception as err:
        logging.error(str(err))

    return {"id": "L_634444597505825671"}
Exemplo n.º 3
0
def check_if_existing_organization(organization_id):
    client = MerakiSdkClient(config.X_CISCO_MERAKI_API_KEY)
    orgs = client.organizations.get_organizations()
    for org in orgs:
        if organization_id == org['id']:
            return True
    return False
Exemplo n.º 4
0
def main():
    """
        The API key and Organization name must be configured as environmental variables
        First obtain the numerical Org ID from the Org name specified, then dump the 
        devices for that Org as YAML and exit.
    """
    x_cisco_meraki_api_key = os.environ.get(KEYNAME)

    if not x_cisco_meraki_api_key:
        print(
            'Ops! you need to set environmental variable, {} to your cisco Meraki API key'
            .format(KEYNAME))
        return

    meraki = MerakiSdkClient(x_cisco_meraki_api_key)

    org_id = get_org_id(dashboard=meraki, org_name=os.environ.get(ORGNAME))

    if not org_id:
        print(
            'Ops! you need to set environmental variable, {} to specify the organization name'
            .format(ORGNAME))
        return

    print(yaml.dump(get_devices(dashboard=meraki, organization_id=org_id)))
def calculate(num=None):
    x_cisco_meraki_api_key = 'your meraki key'

    client = MerakiSdkClient(x_cisco_meraki_api_key)

    clients_controller = client.clients
    collect = {}
    network_id = 'your network ID'
    collect['network_id'] = network_id

    client_id = request.args.get('char1')
    print("client_id = ", client_id)

    collect['client_id'] = client_id

    result = clients_controller.get_network_client(collect)

    # print (json.dumps(result, indent=4))
    # print ("==========================")

    last_time = datetime.datetime.fromtimestamp(int(
        result['lastSeen'])).strftime('%Y-%m-%d %H:%M:%S')
    last_ap_mac = result['recentDeviceMac']
    print("last seen", last_time)
    print("AP MAC ", last_ap_mac)

    last_ap_name = ""
    last_lat = ""
    last_lng = ""

    f = open("440-ap-list.txt", 'r')
    lines = f.readlines()
    for line in lines:
        # print (line)
        separate = line.split(' ')
        if last_ap_mac == separate[0]:
            # print (line)
            last_ap_name = separate[1]
            last_lat = separate[2]
            last_lng = separate[3]
    f.close()

    print(last_ap_mac, last_ap_name, last_lat, last_lng, last_time)

    # end of 440-10.py

    return render_template('440-11-map.html',
                           last_ap_mac=last_ap_mac,
                           last_ap_name=last_ap_name,
                           last_lat=last_lat,
                           last_lng=last_lng,
                           last_time=last_time,
                           client_id=client_id)
Exemplo n.º 6
0
    def configMvSense(self):
        if not self.x_cisco_meraki_api_key:
            raise ValueError("É necessário exportar MERAKI_API_KEY para acessar a API")
        if not self.serial:
            raise ValueError("É necessário exportar MERAKI_CAM_SERIAL para acessar a API")

        self.client = MerakiSdkClient(self.x_cisco_meraki_api_key)

        self.mv_sense_controller = self.client.mv_sense

        #Configuring Opitions
        self.collect['serial'] = self.serial
        self.collect['object_type'] = self.object_type
Exemplo n.º 7
0
def main():
    config = ConfigParser() # using a .ini file to hide my personal home meraki api key :)
    ini = config.read('config.ini') # reading ini file
    x_cisco_meraki_api_key = str(config.get('config', 'api_key')) # opening the .ini file to get the api key 

    meraki = MerakiSdkClient(x_cisco_meraki_api_key) # the MerakiSdkClient is what setsup the API calls for you
    orgs = meraki.organizations.get_organizations() # setting up objerct to get all orginizations
    params = {} # creating empty dict
    params["organization_id"] = str(orgs[0]['id']) # adding my house org ID to the dict. The dict is required when sending params with the API
    nets = meraki.networks.get_organization_networks(params) # getting my orgs using params dict
    params["network_id"] = str(nets[0]['id']) # then adding the network id I pulled to params for later use

    # lets make my home equipment blink! This is an example from merakis quick start SDK
    blink = BlinkNetworkDeviceLedsModel()
    blink.duration = 40
    blink.period = 160
    blink.duty = 50

    x = meraki.devices.get_network_devices(params["network_id"])# Here I used devices.get_network_devices and used the network_id in params to pull them all down

    # we can see I have 3 meraki devices 
    pprint(x)

    # in order to make them blink we have to pass in another param that I added according to the doc
    params['blink_network_device_leds'] = blink

    try:
        # here we loop through each device getting the serial number and then running the blink_network_device_leds api.
        # for each device the serial number will get ovewritten in the params dict before running the API call.
        for i in x: 
            params['serial'] = i['serial']
            result = meraki.devices.blink_network_device_leds(params)
            print(result)
    except APIException as e:
        print(e)

    ##### bonous for fun
    # simple way to use the SDK to get the ips of all the devices on the network
    ip = []
    devices = {}
    devices["network_id"] = str(nets[0]['id'])
    try:
        result = meraki.clients.get_network_clients(devices)
        for i in result:
            ip.append(i['ip'])
        pprint(result)
        print(ip)
    except APIException as e:
        print(e)
Exemplo n.º 8
0
def getMerakiSandboxId():

    """ Imports the DevNet organization ID from the DevNet Sandbox. Import the
    function using:

        $ 'from MerakiDevNetID import getMerakiSandboxId as ID'

    I've tried to make the script self-sufficient and it should just work for as
    long as the sandbox is operational - SC """

    from meraki_sdk.meraki_sdk_client import MerakiSdkClient

    key = "6bec40cf957de430a6f1f2baa056b99a4fac9ea0"
    meraki = MerakiSdkClient(key)
    orgs = meraki.organizations.get_organizations()

    for org in orgs:
        if org['name'] == "DevNet Sandbox":
            sBox = org['id']
    return sBox
def install_configuration(api_key, network_id, file_name, device_policy,
                          group_policy_id):

    # define meraki sdk client
    meraki = MerakiSdkClient(api_key)

    number_of_clients = 0
    # define total number clients
    with open(file_name + '.txt') as f:
        number_of_clients = sum(1 for _ in f)

    # This is a list of dict. Each dict contains client's info
    dictlist = [{} for i in range(0, number_of_clients)]

    # open file with the config [format = mac;name ]
    f = open(file_name + '.txt', 'r')

    for i in range(0, number_of_clients):
        # create an object of type "ProvisionNetworkClientsModel"
        client = ProvisionNetworkClientsModel()
        # read each line at each iteration
        line = f.readline()
        line_splitted = line.split(";")

        dictlist[i]["network_id"] = network_id
        # Populate client info
        client.mac = line_splitted[0].rstrip("\n")
        client.name = line_splitted[1].rstrip("\n")
        client.device_policy = device_policy
        client.group_policy_id = group_policy_id
        dictlist[i]["provision_network_clients"] = client

    for i in range(0, number_of_clients):
        try:
            result = meraki.clients.provision_network_clients(dictlist[i])

        except APIException as e:
            print(e)

    # close file
    f.close()
Exemplo n.º 10
0
def main():

    """ Imports the DevNet organization ID from the DevNet Sandbox.

    I've tried to make the script self-sufficient and it should just work for as
    long as the sandbox is operational.

        key = 6bec40cf957de430a6f1f2baa056b99a4fac9ea0
        meraki = MerakiSdkClient(key)
        orgs = meraki.organizations.get_organizations()

    SC"""

    from meraki_sdk.meraki_sdk_client import MerakiSdkClient

    key = "6bec40cf957de430a6f1f2baa056b99a4fac9ea0"
    meraki = MerakiSdkClient(key)
    orgs = meraki.organizations.get_organizations()

    for org in orgs:
        if org['name'] == "DevNet Sandbox":
            print(f"The {org['name']} has been found under ID {org['id']}")
Exemplo n.º 11
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from . import config


from meraki_sdk.meraki_sdk_client import MerakiSdkClient


def check_if_existing_organization(organization_id):
    client = MerakiSdkClient(config.X_CISCO_MERAKI_API_KEY)
    orgs = client.organizations.get_organizations()
    for org in orgs:
        if organization_id == org['id']:
            return True
    return False


def check_if_network_id_in_organization(organizationDict)
    client = MerakiSdkClient(config.X_CISCO_MERAKI_API_KEY)
    if organizationDict:
        networks = client.networks.get_organization_networks(organizationDict)
        if networks:
            return True

    return False
Exemplo n.º 12
0
		file.write("\t# MR L3 firewall\n")
		file.write("\t# https://dashboard.meraki.com/api_docs#update-the-l3-firewall-rules-of-an-ssid-on-an-mr-network\n")
		file.write("\tputurl = 'https://api.meraki.com/api/v0/networks/{0}/ssids/"+str(row['number'])+"/l3FirewallRules'.format(str(networkid))\n")
		file.write("\tdashboard = session.put(puturl, json="+str({"rules":myRules,"allowLanAccess":True})+", headers=headers)\n")
		file.write("\n")
	

from dotenv import load_dotenv
load_dotenv()
load_dotenv(dotenv_path=os.path.join(os.path.expanduser("~"),".meraki.env"))

parser = argparse.ArgumentParser(description='Backup a Meraki config to an offline file.')
parser.add_argument('orgName', help='The name of a Meraki organisation')
args = parser.parse_args()

meraki = MerakiSdkClient(os.getenv("x_cisco_meraki_api_key"))
orgid=get_org_id(meraki,args.orgName)

with open('meraki-restore.py', 'w') as file:
	write_restore_header(file);

	file.write("# Edit script below this line to control what is #restored.\n");
	file.write("\n");

	file.flush()

	write_admins(file,meraki, orgid);
	write_mx_vpn_fw_rules(file,meraki,orgid)
	write_snmp_settings(file,meraki,orgid)
	write_non_meraki_vpn_peers(file,meraki,orgid)
Exemplo n.º 13
0
def backup_network(ARG_ORGID, NET_ID, ARG_APIKEY, USER):

    meraki = MerakiSdkClient(ARG_APIKEY)
    dirname = os.path.dirname(__file__)
    abspath = os.path.abspath(__file__)
    log_file = os.path.abspath(__file__ +
                               "/../../logs/{}_log_file.log".format(USER))
    filename = os.path.join(dirname,
                            '{}_meraki_restore_network.py'.format(USER))

    with io.open(filename, 'w', encoding='utf-8', errors='ignore') as file:
        write_restore_header(file)
        f = open(log_file, 'w')
        print('Starting Backup', file=f)
        f.flush()
        print('Writing script file {}_meraki_restore_network.py'.format(USER),
              file=f)
        f.flush()
        file.write(
            "# Edit script below this line to control what is #restored.\n")
        file.write("\n")
        file.flush()

        print('Writing admins', file=f)
        f.flush()
        write_admins(file, meraki, ARG_ORGID)
        print('Writing mx_vpn_fw_rules', file=f)
        f.flush()
        write_mx_vpn_fw_rules(file, ARG_ORGID, f, ARG_APIKEY)
        print('Writing snmp_settings', file=f)
        f.flush()
        write_snmp_settings(file, meraki, ARG_ORGID)
        print('Writing non_meraki_vpn_peers', file=f)
        f.flush()
        write_non_meraki_vpn_peers(file, meraki, ARG_ORGID)

        myNetwork = meraki.networks.get_network(NET_ID)
        row = (myNetwork)

        if row['type'] == 'systems manager':
            print('Backup won t be able to restore System Manager settings',
                  file=f)
            pass
        if row['tags'] is None:
            del row['tags']

        jsonModel = {
            "name": "",
            "disableMyMerakiCom": False,
            "disableRemoteStatusPage": False,
            "type": "appliance switch wireless",
        }

        a = row['productTypes']
        separator = ', '
        b = (separator.join(a))
        nettype = b.replace(',', '')
        status = "Restoring network " + \
            row['name']+' in new network '+row['name']+'-restore'
        netName = row['name'] + '-restore'
        disableMyMerakiCom = row['disableMyMerakiCom']
        disableRemoteStatusPage = row['disableRemoteStatusPage']
        jsonModel.update({
            "type": nettype,
            'name': netName,
            "disableMyMerakiCom": disableMyMerakiCom,
            "disableRemoteStatusPage": disableRemoteStatusPage
        })

        payload = (str(jsonModel))

        file.write("# Add Network: " + row['name'] + '-restore' "\n")
        file.write("\tprint('" + status + "',file=f)\n")
        file.write("\tf.flush()\n")
        file.write("\ttry:\n")
        file.write(
            "\t# https://dashboard.meraki.com/api_docs#create-a-network\n")
        file.write(
            "\t\tposturl = 'https://api.meraki.com/api/v0/organizations/{0}/networks'.format(str(ARG_ORGID))\n"
        )
        file.write("\t\tdashboard = session.post(posturl, json=" + payload +
                   ", headers=headers)\n")
        file.write("\t\tdashboard.raise_for_status()\n")
        file.write("\t\tnetworkid=dashboard.json()['id']\n")
        file.write("\n")

        try:
            print('Writing mx vlans', file=f)
            f.flush()
            write_mx_vlans(file, meraki, f, row['id'])
        except:
            print("warning: no mx VLANs", file=f)
            f.flush()
        try:
            print('Writing mx cellular fw rules', file=f)
            f.flush()
            write_mx_cellular_fw_rules(file, meraki, row['id'])
        except:
            print("warning: no mobile firewall rules", file=f)
            f.flush()
        try:
            print('Writing mx l3 fw rules', file=f)
            f.flush()
            write_mx_l3_fw_rules(file, meraki, row['id'])
        except:
            print("warning: no MX firewall rule", file=f)
            f.flush()
        try:
            print('Writing vpn settings', file=f)
            f.flush()
            write_vpn_settings(file, meraki, row['id'])
        except:
            print("warning: no VPN settings", file=f)
            f.flush()
        try:
            print('Writing ssid settings', file=f)
            f.flush()
            write_ssid_settings(file, meraki, row['id'], f)
        except:
            print("warning: no WiFi settings", file=f)
            f.flush()
        try:
            print('Writing device properties', file=f)
            f.flush()
            write_devices_props(file, meraki, row['id'])
        except:
            print("warning: no devices", file=f)
            f.flush()

        # End of First Function block
        file.write("\texcept requests.exceptions.HTTPError as err:\n")
        file.write("\t\tprint(err,file=f)\n")
        file.write(
            "\t\tprint('Can not add network " + row['name'] +
            " - it probably already exists. Change the Network name and make a new backup.',file=f)\n"
        )
        file.write(
            "\tprint('Restoring Complete, move your switchs to the new network and restore the switch configuration.',file=f)\n"
        )
        file.write("\tf.flush()\n")
        file.write("\tf.close()\n")
        file.write("\n")
        file.write("\n")

        # Start second Function block
        file.write("def restore_switchports(ARG_APIKEY,USER):\n")
        file.write("\tabspath = os.path.abspath(__file__)\n")
        file.write("\tlog_file = os.path.abspath(__file__  + "
                   "'/../../logs/{}_log_file.log'.format(USER)"
                   ")\n")
        file.write("\tf = open(log_file, 'w')\n")
        file.write("\n")
        file.write("\theaders = {\n")
        file.write("\t\t'x-cisco-meraki-api-key': ARG_APIKEY,\n")
        file.write("\t\t'Content-Type': 'application/json',\n")
        file.write("\t\t'Accept': 'application/json',\n")
        file.write("\t\t}\n")
        file.write("\n")
        file.write("\tsession = requests.Session()\n")
        file.write("\n")
        file.write("\n")
        file.write("\ttry:\n")
        file.write("\t\tprint('Starting restoring switchports',file=f)\n")
        file.write("\t\tf.flush()\n")

        try:
            print('Writing switch ports', file=f)
            f.flush()
            write_mydevices(file, row['id'], ARG_APIKEY, f)
        except:
            print(
                "No Switchs found or there was an error writing the configuration.",
                file=f)
            f.flush()

        file.write("\texcept requests.exceptions.HTTPError as err:\n")
        file.write("\t\tprint(err,file=f)\n")
        file.write(
            "\t\tprint('There was an error restoring the switchs configuration, check the logs for more details.',file=f)\n"
        )
        file.write(
            "\tprint('Restoring Switch configuration complete.',file=f)\n")
        file.write("\tf.flush()\n")
        file.write("\tf.close()\n")
        file.write("\n")
        file.flush()
        print('Writing complete, check the script before restore.', file=f)
    f.flush()
    f.close()
Exemplo n.º 14
0
#      arg2 Excel File location - String       #
#----------------------------------------------#



# Library Includes
import xlrd 
import sys
from os.path import isfile
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from meraki_sdk.exceptions.api_exception import APIException



#Global Variables
meraki_api = MerakiSdkClient(str(sys.argv[1]))
File_location = str(sys.argv[2])
switch_ports_controller = meraki_api.switch_ports
devices_controller = meraki_api.devices

#Definitions
	#return workbook based on filename
	#after checking if it exists
def get_excel_workbook_object(fname):
	if not isfile(fname):
		print ('File doesnt exist: ',fname)

    # Open the workbook and return object
	wrkbk = xlrd.open_workbook(fname)
	return wrkbk
Exemplo n.º 15
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient

X_Cisco_Meraki_API_Key = '15da0c6ffff295f16267f88f98694cf29a86ed87'

MERAKI = MerakiSdkClient(X_Cisco_Meraki_API_Key)

ORGS = MERAKI.organizations.get_organizations()

for ORG in ORGS:
    print("Org ID:  {} and OrgName: {}".format(ORG['id'], ORG['name']))

PARAMS = {}
PARAMS["organization_id"] = "549236"

NETS = MERAKI.networks.get_organization_networks(PARAMS)

for NET in NETS:
    print("Network ID: {0:20s}, Name: {1:45s},Tags: {2:<10s}".format(
        NET['id'], NET['name'], str(NET['tags'])))

Devices = MERAKI.devices.get_network_devices("L_646829496481105433")

for DEVICE in Devices:
    print("Device Model: {0:9s}, Serial:{1:14}, MAC:{2:17}, Firmware: {3:12s}".
          format(DEVICE['model'], DEVICE['serial'], DEVICE['mac'],
                 DEVICE['firmware']))
Exemplo n.º 16
0
access_token_request = requests.post(url=Auth_URL, headers=headers, data=DATA, verify=False)
token1 = json.loads(access_token_request.text)
access_token1 = pd.DataFrame(token1, index=token1)
token = access_token1['access_token'][0]

selected_secret_id = input("Which Secret would you like to retrieve? - Please input Secret ID - '1234' for example\n ")

URL = f'https://secretServerURL/SecretServer/api/v1/secrets/{selected_secret_id}/fields/APIkey'
HEADERS = {'Authorization': "Bearer" + " " + f"{token}"}
payload = {}
response = requests.get(url=URL, headers=HEADERS, verify=False, data=payload)
print(json.loads(response.text))

api_key = json.loads(response.text)
# key = json(api_key)
meraki = MerakiSdkClient(api_key)


def mainmenu():
    answer = True
    while True:

        condition = True

        while True:
            purpose = int(input('\nTo view organizations, their networks & devices, press 1\n'
                                'Would you like to manage/update switches, firewalls, or access points?\n' +
                                'For switches, press 2 & hit enter\n' + 'For firewalls, press 3 & hit enter\n' +
                                'For MX vlans, press 4 & hit enter \n'))
            if purpose == 1:
                networkmenu()
Exemplo n.º 17
0
#!/usr/bin/python

from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from meraki_sdk.exceptions.api_exception import APIException
from meraki_sdk.models.policy_enum import PolicyEnum
from meraki_sdk.models.rule_model import RuleModel
from meraki_sdk.models.update_network_l3_firewall_rules_model import UpdateNetworkL3FirewallRulesModel

x_cisco_meraki_api_key = ''
meraki = MerakiSdkClient(x_cisco_meraki_api_key)

mx_l3_firewall_controller = meraki.mx_l3_firewall
networks_controller = meraki.networks

orgs = meraki.organizations.get_organizations()

print(orgs)

id = orgs[1]["id"]

collect = {}
collect['organization_id'] = id
nets = networks_controller.get_organization_networks(collect)
print(nets)

#get rules
#for line in nets:
#    print(line["id"])
#    l3_rules = mx_l3_firewall_controller.get_network_l3_firewall_rules(line["id"])
#    print(l3_rules)
Exemplo n.º 18
0
#!flask/bin/python

# Libraries
from pprint import pprint
from flask import Flask
from flask import json
from flask import request
from flask import render_template
import sys
import getopt
import json
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
import pandas as pd
import requests

dashboard = MerakiSdkClient(
    x_cisco_meraki_api_key='07d4b7f273f84f94f6bc4842207f2eac06276943')

apdev = dashboard.devices.get_network_devices(
    network_id='L_667095694804287796')

############## USER DEFINED SETTINGS ###############
# MERAKI SETTINGS
validator = "EnterYourValidator"
secret = "EnterYourSecret"
version = "2.1"  # This code was written to support the CMX JSON version specified
locationdata = "Location Data Holder"
####################################################
app = Flask(__name__)

# Respond to Meraki with validator
Exemplo n.º 19
0
### Import Needed Libraries
import sys, os, requests, time, json, boto3, collections
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from meraki_sdk.exceptions.api_exception import APIException
from benedict import benedict

### Set Correct Directories
basedir = os.path.abspath(os.path.dirname(__file__))
rootdir = os.path.normpath(os.path.join(basedir, "../"))
imagedir = os.path.normpath(os.path.join(basedir, "../images/"))
### Set proper working directory to import Credentials
sys.path.append('.')
### Import Credential Files
import credentials
### Initialize Meraki SDK
meraki = MerakiSdkClient(credentials.meraki_api_dashboard_key)


#######################################################################################
########   Standalone Functions
#######################################################################################
################################################################
###    GET input if Script runs as standalone
################################################################
def get_input():
    ### GET ORG ID
    #Check if Meraki Org id is into Credentials file
    if credentials.meraki_org_id != "":
        org_id = credentials.meraki_org_id
    else:  # Ask for Credentials Token
        org_id = input(
Exemplo n.º 20
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from tools.api_key import key
from get_organization_id import get_org_id
from tools.sdk_create_organization_network import CreateOrganizationNetworkModel

meraki = MerakiSdkClient(key)
org_id = get_org_id()
network_controller = meraki.networks

params = {}
params['organization_id'] = org_id
params['create_organization_network'] = {
    "name": 'James test',
    "type": "appliance",
    "timeZone": 'Europe/London',
    "tags": 'tag1',
}

network = network_controller.create_organization_network(params)
network_id = network['id']
print(network_id)
Exemplo n.º 21
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient

API_KEY = '15da0c6ffff295f16267f88f98694cf29a86ed87'

MERAKI = MerakiSdkClient(API_KEY)

ORGS = MERAKI.organizations.get_organizations()

PARAMS = {}
PARAMS['organization_id'] = ORGS[0]['id']

NETS = MERAKI.networks.get_organization_networks(PARAMS)

DEVICES = MERAKI.devices.get_network_devices(NETS[2]['id'])

for DEV in DEVICES:
    print('Device Model: {0:9s},Serial: {1:14s}, MAC: {2:17},Firmware: {3:12s}'\
          .format(DEV['model'],DEV['serial'],DEV['mac'],DEV['firmware']))
Exemplo n.º 22
0
from pprint import pprint
from webexteamssdk import WebexTeamsAPI
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from meraki_sdk.exceptions.api_exception import APIException
import requests
import os
# Comment to test git
meraki_api_key = '093b24e85df15a3e66f1fc359f4c48493eaa1b73'
mynetwork = 'L_646829496481100388'

meraki = MerakiSdkClient(meraki_api_key)

#Current versions, note that I changed the "." to "-" after reviewing the list data
msversion = '11-31'
mrversion = '26-6-1'
mxversion = '15-27'
mvversion = '4-0'

checklist = []  #empty list for devices not at current levels
MR_count = 0  #define counter for MR devices
MS_count = 0  #define counter for MS devices
MX_count = 0  #define counter for MX devices
MV_count = 0  #define counter for MV devices

# Get Devices
devices = meraki.devices.get_network_devices(mynetwork)

for i in devices:
    if i["model"][:2] == "MR" and mrversion in i["firmware"]:
        MR_count += 1
    elif i["model"][:2] == "MS" and msversion in i["firmware"]:
Exemplo n.º 23
0
    "date", "entrances_left", "entrances_right", "in_store_new",
    "in_store_total"
]

# Keep looping until process terminates
while True:

    # Connect to elastic database
    es_conn = es_handler.connect_elasticsearch(es_handler.HOST_URL)

    #Find time variables
    epoch_t0 = int(time.time()) - 300  #time 5 minutes ago
    epoch_t1 = int(time.time())  #time right now

    # Make Connection to camera based on API Key
    client = MerakiSdkClient(MERAKI_API_KEY)
    mv_sense_controller = client.mv_sense
    # Can select between PERSON and VEHICLE. we are counting people
    object_type = ObjectTypeEnum.PERSON

    # Create collection that has values needed to query camera API
    # serial number of the camera, time frame and what we wish to count (i.e. people)
    collect = {
        'serial': CAMERA_SERIAL,
        't_0': epoch_t0,
        't_1': epoch_t1,
        'object_type': object_type
    }

    try:
        # Run the API call and get information based on values specified in collect
Exemplo n.º 24
0
    table.add_column("SNR", justify="center", style="cyan", no_wrap=True)
    for rogueBssid in rogue['bssids']:
        for observer in rogueBssid['detectedBy']:
            if rogueBssid['bssid'] == bssid:
                table.add_row(observer['name'], observer['device'],
                              str(observer['rssi']))
    console = Console()
    console.print(table)


if __name__ == '__main__':
    # User defind variables
    roguesPerPage = 20
    minimumRssi = 1
    # Initializing Meraki SDK
    meraki = MerakiSdkClient(os.environ.get('MERAKI_KEY'))
    NETWORK_ID = SelectNetwork()
    timeFrame = SelectTimeFrame()
    userInput = ""
    rogues = []
    inventory = meraki.devices.get_network_devices(NETWORK_ID)
    allRogues = meraki.networks.get_network_air_marshal(
        {'network_id': NETWORK_ID})
    filteredRogues = FilterRogues(allRogues, inventory, timeFrame, minimumRssi)

    while userInput.lower() != "quit":
        print("""\n[green]What would you like to do? Your options are:
    * Enter a SSID you'd like to investigate.
    * Enter a BSSID you'd like to investigate.
    * Enter 'display' to display a list of detected rogue SSIDs.
    * Enter 'quit' to exit the program.\n""")
Exemplo n.º 25
0
    # The achilles heel of the process is that clients associated for more than
    # the searched time span will not return an associated channel.
    # Increasing the time span will increase the running time of the code, while
    # decreasing it will increase the number of unknown clients.
    channel = '666'
    for event in events:
        if 'channel' in event['details'].keys():
            channel = event['details']['channel']
    return (channel)


if __name__ == '__main__':
    # Debug mode
    isDebug = False
    # Initializing Meraki SDK
    meraki = MerakiSdkClient(os.getenv('x_cisco_meraki_api_key'))
    NETWORK_ID = SelectNetwork()

    clients_2 = []
    clients_5 = []
    clients_5_on_2 = []
    clients_error = []
    allClients = GetAllClients()
    print('\nReceived a total of %s clients\n' % len(allClients))
    for step in track(range(len(allClients))):
        AnalyzeClient(allClients[step])

    # Summarize the numbers
    wirelessClientCount = len(clients_5) + len(clients_2) + len(clients_error)
    clients_2_num = len(clients_2)
    clients_5_num = len(clients_5)
Exemplo n.º 26
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient

#Cisco DevNet Sandbox Meraki API Key
X_CISCO_MERAKI_API_KEY = "15da0c6ffff295f16267f88f98694cf29a86ed87"

#Establish a new client connection to the Meraki REST API
MERAKI = MerakiSdkClient(X_CISCO_MERAKI_API_KEY)

#Get a list of all the organizations for the Cisco DevNet account
ORGS = MERAKI.organizations.get_organizations()
print("-" * 95)
for ORG in ORGS:
    print("Org id: {} and Org Name: {}".format(ORG["id"], ORG["name"]))
print("-" * 95)

ORG_ID = {}
ORG_ID["organization_id"] = str(ORG["id"])  # Demo org

#Get a list of all the networks for the Cisco DevNet organization
NETS = MERAKI.networks.get_organization_networks(ORG_ID)
for NET in NETS:
    print("Network ID: {0:20s}, Name: {1:45s},Tags: {2:<10s}".format(\
        NET["id"], NET["name"], str(NET["tags"])))

print("-" * 95)
NET_ID = input("Enter network ID for details: ")
print("-" * 95)

# Get a list of all the devices that are part of the Always On Network
DEVICES = MERAKI.devices.get_network_devices(str(NET_ID))
for DEVICE in DEVICES:
Exemplo n.º 27
0
#importing MerakiSDK Client, this client is what sets up our whole connection
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from pprint import pprint

token = "deeb656da181f4f3c63adbde7ff2b64ae8e558d4"  # token generated in portal https://n201.meraki.com/o/Ugi9qb/manage/users/edit?only_path=false&protocol=https
meraki = MerakiSdkClient(
    token
)  # set variable meraki and this is equal the Connection OBJECT (connecting into MERAKI)
# after = specify MerakiSdkClient and use token inside prentesise, this will handle all authentication, storing token for all requests

orgs = meraki.organizations.get_organizations(
)  # Store list of ORGANIZATIONS in variable called "orgs"

pprint(orgs)
Exemplo n.º 28
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
import json
from pprint import pprint

token = "7b750b19efea8ee6d0949de5783d99359dc1a381"
meraki = MerakiSdkClient(token)

orgs = meraki.organizations.get_organizations()
pprint(orgs)

for orgName in orgs:
    if orgName['name'] == 'DevNet Sandbox':
        orgid = orgName['id']
print(orgid)
Exemplo n.º 29
0
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from meraki_sdk.exceptions.api_exception import APIException
from operator import itemgetter
import copy
from _config import *
import json

client = MerakiSdkClient(apikey)


def show_enabled(e_stat):
    if e_stat is True:
        return "Yes"
    else:
        return "No"


def xstr(s):
    return '' if s is None else str(s)


def format_data(srcdata):
    odata = ""
    widths = [max(map(len, col)) for col in zip(*srcdata)]
    for row in srcdata:
        odata += "  ".join((val.ljust(width) for val, width in zip(row, widths))) + "\n"

    return odata


def resolve_arg(arg, datalist):