def get_network_status(network): """ Iterate through each device in each network, check status of device/uplink and set variable 'network_status' to "Down" if applicable if device/uplink is down, skip rest of loop, print findings, and continue with next network Args: network: Returns: A dictionary containing the network name and status. """ network_status = "Up" devices = meraki.getnetworkdevices(config['api_key'], network['id'], suppressprint=True) for device in devices: if network_status == "Down": break uplinks = meraki.getdeviceuplink(config['api_key'], network['id'], device['serial'], suppressprint=True) for uplink in uplinks: if uplink['status'] == "Failed": network_status = "Down" break return {"name": network['name'], "status": network_status}
def main(*args, **kwargs): pp = pprint.PrettyPrinter(width=50, compact=True) # Use your own API key for the Meraki dashboard API api_key = "your_api_key" my_orgs = meraki.myorgaccess(api_key) for org in my_orgs: if 'DevNet Sandbox' in org['name']: my_networks = meraki.getnetworklist(api_key, org['id']) break for network in my_networks: if 'DevNet Always On Read Only' in network['name']: my_net_devices = meraki.getnetworkdevices(api_key, network['id']) networkid = network['id'] break for device in my_net_devices: if 'MV' in device['model']: camera_snapshot = getcamerasnapshot(api_key, networkid, device['serial']) break pp.pprint(camera_snapshot)
def meraki_snapshots(net_id, time=None, filters=None): # Get devices of network and filter for MV cameras devices = meraki.getnetworkdevices(merakiapikey, net_id, suppressprint=True) if devices: cameras = [device for device in devices if device['model'][:2] == 'MV'] # Assemble return data snapshots = [] for camera in cameras: # Remove any cameras not matching filtered names serial = camera['serial'] name = camera['name'] if 'name' in camera else camera['mac'] if filters and filters.lower() != serial.lower(): continue # Get video link response = get_camera_uplink(merakiapikey, net_id, camera["serial"], time) video_link = response.json()['url'] # Get snapshot link response = get_camera_screenshot(merakiapikey, net_id, camera["serial"], time) # print(serial, response.content.decode("utf-8")) # Possibly no snapshot if camera offline, photo not retrievable, etc. if response.ok: snapshots.append((name, response.json()['url'], video_link)) return snapshots else: return []
def get_network_devices(self, net_id: str): """ wrap getnetworkdevices with lru """ devices = meraki.getnetworkdevices(self.apikey, net_id, suppressprint=True) return devices
def main(argv): # Set default values for command line arguments api_key = org_id = arg_mode = None # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:o:m:') except getopt.GetoptError: print_help() sys.exit(2) for opt, arg in opts: if opt == '-h': print_help() sys.exit() elif opt == '-k': api_key = arg elif opt == '-o': org_id = arg elif opt == '-m': arg_mode = arg # Check if all required parameters have been input if api_key == None or org_id == None: print_help() sys.exit(2) # Assign default mode to "simulate" unless "commit" specified if arg_mode != 'commit': arg_mode = 'simulate' # Get list of current networks in org networks = meraki.getnetworklist(api_key, org_id) # Iterate through all networks for network in networks: # Skip if network does not have the tag "ap_reboot" if network['tags'] is None or 'ap_reboot' not in network['tags']: continue # Iterate through a "ap_reboot" network's devices devices = meraki.getnetworkdevices(api_key, network['id']) # Reboot APs for device in devices: if "MR" in device['model']: logger.info('Rebooting ' + device['serial']) rebootdevice(api_key, network['id'], device['serial']) time.sleep(0.2)
def getDevices(nwlist): deviceSerialList=[] try: logger.info('Searching for Devices Initated') for nw in nwlist: devicelist = meraki.getnetworkdevices(config.meraki_api, nw, suppressprint=True) logger.info('Device List Has Been Retrieved for %(nw)s ', {'nw':nw}) for devices in devicelist: deviceSerialDict = {} deviceSerialDict['serial'] = devices['serial'] deviceSerialDict['networkId'] = devices['networkId'] deviceSerialList.append(deviceSerialDict) if len(deviceSerialList) != 0: return deviceSerialList else: logger.error('No Device in the Network') return None except Exception as err: logger.error("ERROR in Retrieving Devices", exc_info=True) return ("ERROR in Retrieving Devices" + str(err))
def merakiclients(): APIKEY = os.getenv("MERAKI_API_KEY") devices = list() clients = list() mOrgs = meraki.myorgaccess(APIKEY) for org in mOrgs: for net in meraki.getnetworklist(APIKEY, org["id"]): devices += meraki.getnetworkdevices(APIKEY, net["id"]) for device in devices: clients += meraki.getclients(APIKEY, device["serial"]) blobclient = BlobServiceClient.from_connection_string(os.getenv("BLOB_CONNECTION_STRING")) container = blobclient.get_container_client(os.getenv("MERAKI_BLOB_CONTAINER")) blobname = "clients-{}.json".format(datetime.date.today().isoformat()) try: container.upload_blob(blobname, data=json.dumps(clients, indent=2)) except Exception as e: print(e) response = "Uploaded {} containing {} clients".format(blobname, len(clients)) return response
def main(argv): # Set default values for command line arguments api_key = org_id = arg_tag = arg_policy = arg_mode = None # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:o:t:p:m:') except getopt.GetoptError: print_help() sys.exit(2) for opt, arg in opts: if opt == '-h': print_help() sys.exit() elif opt == '-k': api_key = arg elif opt == '-o': org_id = arg elif opt == '-t': arg_tag = arg elif opt == '-p': arg_policy = arg elif opt == '-m': arg_mode = arg # Check if all required parameters have been input if api_key == None or org_id == None or arg_tag == None or arg_policy == None: print_help() sys.exit(2) # Assign default mode to "simulate" unless "commit" specified if arg_mode != 'commit': arg_mode = 'simulate' # Get org's inventory inventory = meraki.getorginventory(api_key, org_id) # Filter for only MV devices cameras = [device for device in inventory if device['model'][:2] in ('MV') and device['networkId'] is not None] # Gather the networks (IDs) where cameras have been added camera_network_ids = set([camera['networkId'] for camera in cameras]) logger.info('Found a total of {0} cameras added to {1} networks in this Dashboard organization'.format(len(cameras), len(camera_network_ids))) # Iterate through camera networks and find cameras with specified tag camera_macs = [] for net_id in camera_network_ids: devices = meraki.getnetworkdevices(api_key, net_id) for device in devices: if device['model'][:2] == 'MV' and 'tags' in device and arg_tag in device['tags']: camera_macs.append(device['mac']) logger.info('Found {0} cameras with the tag "{1}"'.format(len(camera_macs), arg_tag)) # Get list of all networks in org networks = meraki.getnetworklist(api_key, org_id) # Iterate through all networks, looking for cameras as clients, and apply group policy for network in networks: # Get the Meraki devices in this network devices = meraki.getnetworkdevices(api_key, network['id']) # Filter for just the first two characters of each device model device_models = [device['model'][:2] for device in devices] # Is there an MX here? If so, get its index in the list of devices if 'MX' in device_models: # We found the MX device in the network mx_device = devices[device_models.index('MX')] else: # No MX in this network, doesn't make sense to apply a group policy to wired clients (cameras), so move on continue # Get list of MX clients clients = meraki.getclients(api_key, mx_device['serial'], timestamp=2592000) # Filter for MAC addresses of these clients client_macs = [client['mac'] for client in clients] # Cameras in this network = intersection of clients in this network and cameras in the org network_cameras = set(client_macs).intersection(camera_macs) # Assign group policy to these cameras in the network if network_cameras: # Gather group policies of network gps = meraki.getgrouppolicies(api_key, network['id']) # Get human-readable names of all group policies gp_names = [gp['name'] for gp in gps] # Look for the group policy gp_camera = gps[gp_names.index(arg_policy)] # Assign that group policy (by ID) to the camera by MAC address for mac in network_cameras: if arg_mode == 'commit': meraki.updateclientpolicy(api_key, network['id'], mac, policy='group', policyid=gp_camera['groupPolicyId']) logger.info('Assigning group policy "{0}" on network "{1}" for MV camera {2}'.format(arg_policy, network['name'], mac)) else: logger.info('Simulating group policy "{0}" on network "{1}" for MV camera {2}'.format(arg_policy, network['name'], mac))
apikey, apidata, ['name', 'id', 'tags', 'timeZone', 'type'], "Network", "id") apidata = m.getnetworkdetail(apikey, selectedNetwork, suppressprint=True) dummy = explore_next(apikey, apidata, ['name', 'id', 'tags', 'timeZone', 'type'], justPrint=True) print("please select:\n1: Get Network Devices\n2: Update Network") user_input = input("##: ") if user_input == "1": apidata = m.getnetworkdevices(apikey, selectedNetwork, suppressprint=True) # Selection │ address│lanIp│lat│lng│mac │ model│ name│ networkId│serial│tags│wan1Ip│wan2Ip selectedDevice = explore_next( apikey, apidata, ['address', 'lanIp', 'mac', 'model', 'name', 'serial', 'tags'], "Device", "serial") apidata = m.getdevicedetail(apikey, selectedNetwork, selectedDevice, suppressprint=True) dummy = explore_next( apikey, apidata, ['address', 'lanIp', 'mac', 'model', 'name', 'serial', 'tags'],
if len(sys.argv) == 1: print('Usage: update-policy.py <api-key> (optional <network ID>)') exit() else: apikey = sys.argv[1] #Takes a hard-coded network ID - needs to be of type N_ or L_ if len(sys.argv) == 2: print('No network passed, assuming all networks in all organisations') #TODO: get list of networks in org, pass them recursively below #getnetworks() print('not currently supported, quitting...') exit() elif len(sys.argv) >= 3: netid = sys.argv[2] if netid[0] not in ('N', 'L'): print('Network ID should begin with N_ or L_') print('Quitting...') exit() devList = meraki.getnetworkdevices(apikey, netid, suppressprint=True) for devs in devList: serial = devs['serial'] print('\t\tSerial: ', serial) clientList = meraki.getclients(apikey, serial, timestamp=1200, suppressprint=True) for client in clientList: clientid = client['id'] checkclientpolicy(netid, clientid)
##### START EDITING ##### # Call to return the inventory for an organization # One line similar to above line 33's call on meraki.getnetworklist() inventory = meraki.getorginventory() ###### END EDITING ###### ######################### # Filter out used devices already allocated to networks unused = [device for device in inventory if device['networkId'] is None] print('Part 2: found total of {0} unused devices in inventory\n'.format( len(unused))) # 3. Claim a device into a network # Check if network already contains a device my_network_devices = meraki.getnetworkdevices(my_key, my_netid) # No device in network yet if len(my_network_devices) == 0: # Pick a random AP from the unused inventory my_ap = random.choice(unused) my_serial = my_ap['serial'] print( 'Part 3: found an unused AP from inventory, with serial number {0}\n'. format(my_serial)) ######################### ##### START EDITING ##### # Call to claim a device into a network # Only one line needs to be filled here, with the same indentation (4 spaces) meraki.adddevtonet()
orgid = myOrgs[0]['id'] print('##### Analizing networks...') myNetworks = meraki.getnetworklist(apikey, orgid) #networkid = myNetworks['id'] # WE DO NOT HAVE PERMISSION TO GET THE INFO FROM NETWORKLIST, BUT WE CAN #USE THE NETWORK ID THEY GAVE US (IN A REAL CASE, THE CODE ABOVE IS CORRECT): networkid = 'N_658651445502946234' ######################## # Get the info from all clients ######################## # Get the serial number of the wifi point (device) # (there were three Cisco wifi points in the venue of the hackathon) devices = meraki.getnetworkdevices(apikey,networkid) serialnum = devices[1]['serial'] # Cisco stand MR53 # Get the info from all clients print('##### Requesting clients data...') clients = meraki.getclients(apikey, serialnum) ######################## # Find our client MAC address ######################## for i in range(len(clients)): name = clients[i]['mdnsName'] #print(name) if name == client_name: identifier = clients[i]['id']
def main(argv): # Set default values for command line arguments api_key = org_id = arg_tag = arg_policy = arg_mode = None # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:o:t:p:m:') except getopt.GetoptError: print_help() sys.exit(2) for opt, arg in opts: if opt == '-h': print_help() sys.exit() elif opt == '-k': api_key = arg elif opt == '-o': org_id = arg elif opt == '-t': arg_tag = arg elif opt == '-p': arg_policy = arg elif opt == '-m': arg_mode = arg # Check if all required parameters have been input if api_key == None or org_id == None or arg_tag == None or arg_policy == None: print_help() sys.exit(2) # Assign default mode to "simulate" unless "commit" specified if arg_mode != 'commit': arg_mode = 'simulate' # Get org's inventory inventory = meraki.getorginventory(api_key, org_id) # Filter for only MV devices cameras = [ device for device in inventory if device['model'][:2] in ('MV') and device['networkId'] is not None ] # Gather the networks (IDs) where cameras have been added camera_network_ids = set([camera['networkId'] for camera in cameras]) logger.info( 'Found a total of {0} cameras added to {1} networks in this Dashboard organization' .format(len(cameras), len(camera_network_ids))) # Iterate through camera networks and find cameras with specified tag camera_macs = [] for net_id in camera_network_ids: devices = meraki.getnetworkdevices(api_key, net_id) for device in devices: if device[ 'model'][: 2] == 'MV' and 'tags' in device and arg_tag in device[ 'tags']: camera_macs.append(device['mac']) logger.info('Found {0} cameras with the tag "{1}"'.format( len(camera_macs), arg_tag)) # Get list of all networks in org networks = meraki.getnetworklist(api_key, org_id) # Iterate through all networks, looking for cameras as clients, and apply group policy for network in networks: # Get the Meraki devices in this network devices = meraki.getnetworkdevices(api_key, network['id']) # Filter for just the first two characters of each device model device_models = [device['model'][:2] for device in devices] # Is there an MX here? If so, get its index in the list of devices if 'MX' in device_models: # We found the MX device in the network mx_device = devices[device_models.index('MX')] else: # No MX in this network, doesn't make sense to apply a group policy to wired clients (cameras), so move on continue # Get list of MX clients clients = meraki.getclients(api_key, mx_device['serial'], timestamp=2592000) # Filter for MAC addresses of these clients client_macs = [client['mac'] for client in clients] # Cameras in this network = intersection of clients in this network and cameras in the org network_cameras = set(client_macs).intersection(camera_macs) # Assign group policy to these cameras in the network if network_cameras: # Gather group policies of network gps = meraki.getgrouppolicies(api_key, network['id']) # Get human-readable names of all group policies gp_names = [gp['name'] for gp in gps] # Look for the group policy gp_camera = gps[gp_names.index(arg_policy)] # Assign that group policy (by ID) to the camera by MAC address for mac in network_cameras: if arg_mode == 'commit': meraki.updateclientpolicy( api_key, network['id'], mac, policy='group', policyid=gp_camera['groupPolicyId']) logger.info( 'Assigning group policy "{0}" on network "{1}" for MV camera {2}' .format(arg_policy, network['name'], mac)) else: logger.info( 'Simulating group policy "{0}" on network "{1}" for MV camera {2}' .format(arg_policy, network['name'], mac))
for j in org_names_ids: for adm in net_ids_adm: if j[1] == adm[0]: sigla_adm = [j[0]] adm += list(sigla_adm) else: continue for cap in net_ids_captive: if j[1] == cap[0]: sigla_cap = [j[0]] cap += list(sigla_cap) else: continue for net_adm in net_ids_adm: devices = meraki.getnetworkdevices(KEY, net_adm[2]) for device in devices: device_name = device.get('name') device_org = meraki.getorg(KEY, net_adm[0]).get('name') device_serial = device.get('serial') adm_apnames.append(device_name) net_type_adm.append('ADM') adm_orgs.append(device_org) adm_serial.append(device_serial) for net_cap in net_ids_captive: devices_cap = meraki.getnetworkdevices(KEY, net_cap[2]) for device_cap in devices_cap: device_name = device_cap.get('name') device_org = meraki.getorg(KEY, net_cap[0]).get('name') device_serial = device_cap.get('serial') cap_apnames.append(device_name)
def main(argv): # Set default values for command line arguments api_key = org_id = arg_mode = None # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:o:m:') except getopt.GetoptError: print_help() sys.exit(2) for opt, arg in opts: if opt == '-h': print_help() sys.exit() elif opt == '-k': api_key = arg elif opt == '-o': org_id = arg elif opt == '-m': arg_mode = arg # Check if all required parameters have been input if api_key == None or org_id == None: print_help() sys.exit(2) # Assign default mode to "simulate" unless "commit" specified if arg_mode != 'commit': arg_mode = 'simulate' # Get list of current networks in org networks = meraki.getnetworklist(api_key, org_id) # Iterate through all networks for network in networks: # Skip if network does not have the tag "migrate" if network['tags'] is None or 'migrate' not in network['tags']: continue # Iterate through a "migrate" network's switches devices = meraki.getnetworkdevices(api_key, network['id']) # Use two dictionaries to keep track of names (keys) and serials (values) old_switches = {} new_switches = {} for device in devices: if device['model'] == OLD_MODEL: old_switches[device['name']] = device['serial'] elif device['model'] == NEW_MODEL: new_switches[device['name']] = device['serial'] # Check to make sure there actually are new switches in this network if len(new_switches) == 0: logger.error('{0} has no {1} switches, so skipping'.format( network['name'], NEW_MODEL)) continue else: logger.info('Cloning configs for network {0}'.format( network['name'])) # For networks where new switches have been added with matching names for name in new_switches.keys(): if name in SKIPPED_NAMES: continue # Lookup serial numbers old_switch = old_switches[name] new_switch = new_switches[name] logger.info('Cloning configs from {0} {1} to {2} {3}'.format( OLD_MODEL, old_switch, NEW_MODEL, new_switch)) # Port 1 through 54 (48 LAN, 4 uplinks, 2 stacking, +1 for range ending index) for port in range(1, 48 + 4 + 2 + 1): config = meraki.getswitchportdetail( api_key, old_switch, port) # Clone corresponding new switch if arg_mode == 'commit': # Tags needed to be input as a list if config['tags'] is not None: tags = config['tags'].split() else: tags = [] # Access type port if config['type'] == 'access': meraki.updateswitchport( api_key, new_switch, port, name=config['name'], tags=tags, enabled=config['enabled'], porttype=config['type'], vlan=config['vlan'], voicevlan=config['voiceVlan'], poe=config['poeEnabled'], isolation=config['isolationEnabled'], rstp=config['rstpEnabled'], stpguard=config['stpGuard'], accesspolicynum=config['accessPolicyNumber']) # Trunk type port elif config['type'] == 'trunk': meraki.updateswitchport( api_key, new_switch, port, name=config['name'], tags=tags, enabled=config['enabled'], porttype=config['type'], vlan=config['vlan'], allowedvlans=config['allowedVlans'], poe=config['poeEnabled'], isolation=config['isolationEnabled'], rstp=config['rstpEnabled'], stpguard=config['stpGuard']) logger.info( 'Switch port {0} config cloned'.format(port)) else: logger.info( 'Switch port {0} config clone simulated'.format( port))