def getClients(sns_ip_list,seriallist): #seriallist IS getDevices Function endpoint_pair_list=[] try: logger.info('Search for the Client MAC with Appropriate IP Address has been started, (iterate through devices in the order of MR,MS and MX) => This can be added') for client_ip in sns_ip_list: for serial in seriallist: connected_endpoints = meraki.getclients(config.meraki_api, serial['serial'], timestamp=86400, suppressprint=True) logger.info('Clients have been gathered for %(serial)s ', {'serial': serial['serial']}) for endpoint in connected_endpoints: if endpoint['ip'] == client_ip: logger.info('Device is found connected to %(serial)s MAC Value will be returned', {'serial': serial['serial']}) endpoint_pair = dict() endpoint_pair['mac'] = endpoint['mac'] endpoint_pair['networkId'] = serial['networkId'] endpoint_pair_list.append(endpoint_pair) if len(endpoint_pair_list) == 0: logger.info('Client has not been found for %(serial)s ', {'serial': serial['serial']}) return None else: return endpoint_pair_list except Exception as err: logger.error("ERROR in Retrieving Clients", exc_info=True) return ("ERROR in Retrieving Clients" + str(err))
def get_clients_usage(): clients = meraki.getclients(API_KEY, SERIAL_NUM) for index in clients: query = "'%s', %s, %s, '%s'" %( index['mac'], index['usage']['sent'], index['usage']['recv'], datetime.datetime.now().date()) insert('insert_usage',query)
def getclient(self): """Gets the devices in a meraki organization """ devices = meraki.get_device_statuses(apikey, orgid) """Finds the device(s) the client is connected to and creats a list with the user data and switch name""" for device in devices: client_devices = meraki.getclients(apikey, device['serial']) for client_device in client_devices: if client_device['ip'] == self.client_id: client_details = Client.buildclientdetails( self, client_device, device) elif client_device['mac'] == self.client_id: client_details = Client.buildclientdetails( self, client_device, device) return client_details
def meraki_wifi_clients(): all_clients = {} for ten_minutes in range(1, 7): for ap_name in aps: ap_clients = meraki.getclients(api_key, aps[ap_name], timestamp=ten_minutes * 10 * 60) for client in ap_clients: name = client['description'] if name not in all_clients: all_clients[name] = { 'location': ap_name, 'mac': client['mac'], 'ip': client['ip'], 'last_seen': ten_minutes * 10 } return all_clients
def get_clients(): clientsInfomation = meraki.getclients(API_KEY, SERIAL_NUM) for index in clientsInfomation: # GET Information about an specifit client. client = meraki.getclient(API_KEY, NETWORK_ID, index['id']) query = "'%s', '%s','%s', '%s', '%s', '%s','%s', %s, %s, '%s','%s', '%s'" % ( index['id'], # VARCHAR index['description'], # VARCHAR index['mdnsName'], # VARCHAR index['dhcpHostname'], # VARCHAR index['mac'], # VARCHAR index['ip'], # VARCHAR index['vlan'], # VARCHAR client['firstSeen'], # INT client['lastSeen'], # INT client['manufacturer'], # VARCHAR client['os'], # VARCHAR client['wirelessCapabilities']) # VARCHAR insert('insert_client', query)
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))
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'], justPrint=True) apidata = m.getclients(apikey, selectedDevice, suppressprint=True) #Selection │ description│ dhcpHostname│ id│ ip │ mac│ mdnsName │ usage │ vlan selectedMac = explore_next( apikey, apidata, ['description', 'dhcpHostname', 'ip', 'mac', 'usage', 'vlan'], "Client", "mac") apidata = m.getclientpolicy(apikey, selectedNetwork, selectedMac, suppressprint=True) dummy = explore_next( apikey, apidata, ['description', 'dhcpHostname', 'ip', 'mac', 'usage', 'vlan'], justPrint=True)
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)
# 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'] # We choose a client by its identifier, e.g. Juulia's iPhone print('##### Extracting',client_name,'mac address...') client = meraki.getclient(apikey, networkid, identifier) #, suppressprint=False) client_mac = client['mac']
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))
################# Network Policy Info ############### #Mannually create Policies for Normal Operation and #for restricted Operations on your MX. Set your traffic #fitlering desired in the 'kids' group. g_policy = 'group' n_policy = 'normal' Spolicyid = '102' #No Internet group Policy Fpolicyid = '101' #Kids group Policy ####################################################### ############## Device List ############################ #Dynamically build a list of all devices known by the MX #and that their description field doesn't have 'none' as a value ClientList = meraki.getclients(apikey, serialnum, timestamp=86400, suppressprint=False) N_ClientList = {} for i in range(len(ClientList)): v_description = str(ClientList[i].get('description')) v_mac = ClientList[i].get('mac') if ((v_description.find('None')) < 0): d1 = {v_description: v_mac} N_ClientList.update(d1) ############### Setup the Gui Window #################### root = Tk() root.title("Don't Make Me Press That Button") frame = Frame(root, bg='white', borderwidth=5, relief="ridge")
serials_list = list(reader) serials_file.close() counter_adm = 0 counter_cap = 0 total_counter_adm = 0 total_counter_cap = 0 for i in serials_list: if i[1] == 'ADM': adm.append(i) else: captive.append(i) for i in adm: counter_adm = len(meraki.getclients(API, i[3], 300)) date_raw = str(datetime.utcnow()) date_no_milli = date_raw[:20] date_T = date_no_milli.replace(" ", "T") date_T_Z = date_T.replace(".", "Z") total_counter_adm += counter_adm set_adm_final = [i[2], i[1], i[0], counter_adm, date_T_Z] sorted_adm.append(set_adm_final) for j in captive: counter_cap = len(meraki.getclients(API, j[3], 300)) date_raw = str(datetime.utcnow()) date_no_milli = date_raw[:20] date_T = date_no_milli.replace(" ", "T") date_T_Z = date_T.replace(".", "Z") total_counter_cap += counter_cap set_cap_final = [j[2], j[1], j[0], counter_cap, date_T_Z]