def get_ssid_l3fw_rules(api_key, api_id, ssid_name): api_key=api_key api_id=api_id ssid_name=ssid_name current_networks = meraki.getnetworklist(api_key, api_id,suppressprint=True) for network in current_networks: api_netid = network['id'] ssids = meraki.getssids(api_key, api_netid, suppressprint=True) if str(ssids) == 'None': pass else: ssid_num = len(ssids) for num in range(0,ssid_num-1): if ssids[num]['name'].startswith("Unconfigured SSID"): pass elif ssids[num]['name'].endswith(ssid_name): print(network['name']+','+network['id']+','+ssids[num]['name']) print(' ') g_response=meraki.getssidl3fwrules(api_key, api_netid, ssids[num], suppressprint=False) print(g_response) print('') for rule_num in range(0,len(g_response)): print(rule_num+1, g_response[rule_num]) print('')
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 get_network(api_key, org_id, network_name): networks = meraki.getnetworklist(api_key, org_id, suppressprint=True) for network in networks: if network['name'] == network_name: return network['id'] print('Error: Network Not found: ' + network_name) return None
def get_networks(self): """ wrap getnetworklist with lru """ org_id = self.get_my_org_id() networks = meraki.getnetworklist(self.apikey, org_id, suppressprint=True) return networks
def get_org_bssids(self, org_id): org_networks = meraki.getnetworklist(self.api_key, org_id, suppressprint=True) self.org_inventory = meraki.getorginventory(self.api_key, org_id, suppressprint=True) bssids = {} for network in org_networks: bssids[network['name']] = self.__get_bssids_for_network(network) return bssids
def do_get_network_by_name(networkname): """ This function searches the list of networks in Dashboard and returns the ID of one with a matching name networkname :return: string """ if networkname == "": return "" net_info = meraki.getnetworklist(merakiapikey, merakiorgnum, suppressprint=True) for n in net_info: if n["name"] == networkname: return n["id"] return ""
def replace_ssid_l3fw_rules(api_key, api_id, ssid_name): fwrules=[] api_key=api_key api_id=api_id ssid_name=ssid_name with open(input_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: csv_comment = row['comment'] csv_policy = row['policy'] csv_protocol = row['protocol'] csv_destPort = row['destPort'] csv_destCidr = row['destCidr'] fwrules_data = [{'comment': csv_comment, 'policy': csv_policy, 'protocol': csv_protocol, 'destPort': csv_destPort, 'destCidr': csv_destCidr}] print(fwrules_data[0]) fwrules.append(fwrules_data[0]) resp=input('CAUTION! The existing firewall rules will be replaced. Do you want to add the above rules? [y|n]') while resp in ('y', 'n'): if resp == 'y': current_networks = meraki.getnetworklist(api_key, api_id,suppressprint=True) for network in current_networks: api_netid = network['id'] api_netname = network['name'] ssids = meraki.getssids(api_key, api_netid, suppressprint=True) if str(ssids) == 'None': pass else: ssid_num = len(ssids) for num in range(0,ssid_num-1): if ssids[num]['name'].startswith("Unconfigured SSID"): pass elif ssids[num]['name'].endswith(ssid_name): print(network['name']+','+network['id']+','+ssids[num]['name']) print(' ') print(fwrules) u_response=meraki.updatessidl3fwrules(api_key, network['id'], ssids[num], fwrules, allowlan=None, suppressprint=False) print(u_response) print('') for rule_num in range(0,len(u_response)): print(rule_num+1, u_response[rule_num]) print('') break else: break
def get_serials_of_devices(api_key, org_id): ''' [Get networks in org { "id": "N_24329156", "organizationId": 2930418, "name": "My organization", "timeZone": "America/Los_Angeles", "tags": " tag1 tag2 ", "type": "combined", "disableMyMerakiCom": false } ] [Get devices in org { "mac": "00:11:22:33:44:55", "serial": "Q234-ABCD-5678", "networkId": "N_24329156", "model": "MR34", "claimedAt": 1518365681.0, "publicIp": "123.123.123.1", "name": "My AP" } ] ''' #get network names first and map to IDs temp = {} #{'N_12345':'test network'} #networkIds = [] networks = meraki.getnetworklist(api_key, org_id, suppressprint=True) for network in networks: if 'name' in network: temp[network['id']] = network['name'] inventory = meraki.getorginventory(api_key, org_id, suppressprint=True) #get all APs in org #create new Dict, only include networks with MRs, and add serial to data #devices = [device for device in inventory if device['model'][:2] in ('MR') and device['networkId'] is not None] networkIdDict = { } #{'D-serial':['NID','mac','network name','model','device name']} for device in inventory: if device['serial'] and device['networkId']: #networkIdDict[device['networkId']] = [device['mac'],device['serial'],device['model'],temp[device['networkId']]] networkIdDict[device['serial']] = [ device['networkId'], device['mac'], temp[device['networkId']], device['model'], device['name'] ] return networkIdDict
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 add_network_name(api_key, org_id, df): #start_time = datetime.now() logger.debug("Adding Network names to CSV file") networkNameList = {} networks = meraki.getnetworklist(api_key, org_id, suppressprint=True) for network in networks: if 'name' in network: networkNameList[network['id']] = network['name'] #networkNameList.append([network['id'], network['name']]) for i in df.index: #df.ix[...] is just a locator , i is the index of the row #networkNameList is a dictionary, so networkNameList[ID] will point to the name pair {'ID':'Name} df.ix[i, 'Network Name'] = networkNameList[df.ix[i, 'Network ID']] #print('time: {0}'.format(datetime.now()-start_time)) return df
def getNetwork(orglist): nwlist=[] try: logger.info('Organzations added to OrgList moving to Network List') for orgs in orglist: print(orgs) nws = meraki.getnetworklist(config.meraki_api, orgs, templateid=None, suppressprint=True) #THAT LINE NEEDS TO BE CHANGED, NOW IT IS STATIC FOR ONE ORGANIZATION if nws != None: for nwid in nws: print(nwid['id']) nwlist.append(nwid['id']) logger.info('Network List Has been Retrieved') if len(nwlist) != 0: return nwlist else: logger.error('Network List is Empty') except Exception as err: logger.error("ERROR in Getting Network", exc_info=True) return ("ERROR in Getting Network" + str(err))
def delete_ssid_l3fw_rules(api_key, api_id, ssid_name): api_key=api_key api_id=api_id ssid_name=ssid_name current_networks = meraki.getnetworklist(api_key, api_id,suppressprint=True) for network in current_networks: api_netid = network['id'] ssids = meraki.getssids(api_key, api_netid, suppressprint=True) if str(ssids) == 'None': pass else: ssid_num = len(ssids) for num in range(0,ssid_num-1): if ssids[num]['name'].startswith("Unconfigured SSID"): pass elif ssids[num]['name'].endswith("guru"): print(network['name']+','+network['id']+','+ssids[num]['name']) print(' ') g_response=meraki.getssidl3fwrules(api_key, network['id'], ssids[num], suppressprint=False) for rule_num in range(0,len(g_response)-1): print(rule_num+1, g_response[rule_num]) is_valid=0 while not is_valid : try : r_num = int(input('Enter the rule number of the rule you would like to delete: ')) is_valid = 1 # set it to 1 to validate input and to terminate the while..not loop except ValueError: print ("'%s' Enter the rule number." % e.args[0].split(": ")[1]) del_num=r_num-1 del g_response[del_num] fwrules=g_response[:-2] print(fwrules) u_response=meraki.updatessidl3fwrules(api_key, network['id'], ssids[num], fwrules, allowlan=None, suppressprint=False) # print(u_response) print('') for rule_num in range(0,len(u_response)): print(rule_num+1, u_response[rule_num]) print('')
def main(*args, **kwargs): pp = pprint.PrettyPrinter(width=41, 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_vlans = meraki.getvlans(api_key, network['id']) break pp.pprint(my_vlans)
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
# Inputs ######################## # Name of the device we want to track client_name = 'Hollyhelen.local' # This is an example ######################## # Get the network ID ######################## apikey = "0d79271f7401f39b20630d7de9ad999c594cb403" myOrgs = meraki.myorgaccess(apikey) print(myOrgs) 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
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 lists of templates and networks in org templates = meraki.gettemplates(api_key, org_id) networks = meraki.getnetworklist(api_key, org_id) unbound_networks = [ network for network in networks if 'configTemplateId' not in network ] # Iterate through all templates logger.info(f'Iterating through {len(templates)} templates:') for template in templates: result = get_appliance_service_setting(api_key, template['id'], 'web') # Does template have MX appliance component? if result.ok: web_status = json.loads(result.text)['access'] # Check current config to see if already disabled if web_status == 'blocked': logger.info( f'Appliance web service for template {template["name"]} already disabled/blocked' ) csv_row = [ 'Template', template['name'], template['id'], '?', 'blocked' ] csv_writer.writerow(csv_row) else: # Update configuration if arg_mode == 'commit': logger.info(f'Updating template {template["name"]}...') result = set_appliance_service_setting( api_key, template['id'], 'web', 'blocked') if result.ok: logger.info( f'Blocked remote IPs for web service on template {template["name"]}' ) web_status = json.loads(result.text)['access'] else: logger.error( f'Failed to update appliance web service on {template["name"]}' ) web_status = '?' else: logger.info( f'Simulating update of template {template["name"]}...') # Write result to CSV output file csv_row = [ 'Template', template['name'], template['id'], '?', web_status ] csv_writer.writerow(csv_row) else: # Template without appliance component csv_row = [ 'Template', template['name'], template['id'], '?', 'N/A' ] csv_writer.writerow(csv_row) # Iterate through all unbound networks (networks not associated with a template) logger.info(f'Iterating through {len(unbound_networks)} unbound networks:') for network in unbound_networks: # For appliance networks, check web firewall service if network['type'] in ('appliance', 'combined'): result = get_appliance_service_setting(api_key, network['id'], 'web') web_status = json.loads(result.text)['access'] else: web_status = 'N/A' # If everything already disabled, make note in CSV & continue local_status_disabled = network['disableMyMerakiCom'] if local_status_disabled and web_status in ('blocked', 'N/A'): logger.info( f'Status page for network {network["name"]} already disabled/blocked' ) csv_row = [ 'Network', network['name'], network['id'], 'disabled', web_status ] csv_writer.writerow(csv_row) else: # Update configuration if arg_mode == 'commit': logger.info(f'Updating network {network["name"]}...') result1 = set_network(api_key, network['id'], disableMyMerakiCom=True) if result1.ok: logger.info( f'Disabled local status page for network {network["name"]}' ) local_status_disabled = True else: logger.error( f'Failed to update local status page on network {network["name"]}' ) if network['type'] in ('appliance', 'combined'): result2 = set_appliance_service_setting( api_key, network['id'], 'web', 'blocked') if result2.ok: logger.info( f'Blocked remote IPs for web service on appliance {network["name"]}' ) web_status = json.loads(result2.text)['access'] else: logger.error( f'Failed to update appliance web service on {network["name"]}' ) web_status = '?' else: logger.info( f'Simulating update of network {network["name"]}...') # Write result to CSV output file lsp_status = 'disabled' if local_status_disabled else 'enabled' csv_row = [ 'Network', network['name'], network['id'], lsp_status, web_status ] csv_writer.writerow(csv_row)
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))
from meraki import meraki import logging import time api_key = '##############' org_id = '############' logging.basicConfig(filename='tag_test.log') networks = meraki.getnetworklist(api_key, org_id) input_file = open('test.csv') line_num = 0 for line in input_file: line_num += 1 inputs = line.split(',') #print(inputs) try: new_tags = [inputs[1], inputs[2], inputs[3], inputs[4], inputs[5]] except IndexError: logging.error("Line # {} is not correct".format(line_num)) print("updating {}".format(inputs[0])) try: current_site = next(network for network in networks if network['name'] == inputs[0]) result = meraki.updatenetwork(api_key, current_site['id'], name='', tz='', tags=new_tags) time.sleep(0.5) except (StopIteration, TypeError): logging.error("network {} not found".format(inputs[0]))
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))
# implemented https://stackoverflow.com/questions/11264005/using-a-regex-to-match-ip-addresses-in-python/11264056 numPeriods = theRuleIPs.count(".") numCommas = theRuleIPs.count(",") if numPeriods % 3 != 0: print( "There does not appear to be any IP Addreses in the second line of the input file!" ) sys.exit(1) if numPeriods / 3 != numCommas + 1: print( "Number of commas in IP address list does not match number of IP addresses!" ) sys.exit(1) #obtain all networks in the Org specified by the config variable myNetworks = meraki.getnetworklist(config.meraki_api_key, config.meraki_org_id, None, True) #stop the script if the operator does not agree with the operation being previewed print("About to insert the following IPs: ", theRuleIPs, " in a rule with comment: " + theRuleComment) print("into the following networks:") for theNetwork in myNetworks: theNetworkid = theNetwork["id"] theNetworkname = theNetwork["name"] print(theNetworkid, " ", theNetworkname) if not input("Procced? (y/n): ").lower().strip()[:1] == "y": sys.exit(1) for theNetwork in myNetworks: theNetworkid = theNetwork["id"] #comment the 3 lines below if you do not want to filter out networks whose name matches that condition if theNetwork["name"].startswith('z') or theNetwork["name"].endswith(
#!/usr/bin/python3.6 from meraki import meraki apikey = "myAPIkey" # get API key from Meraki dashboard orgs = meraki.myorgaccess(apikey, suppressprint=True) company = "myCompany" # insert company name c = list(filter(lambda o: o.get('name') == company, orgs)) if list: c = c[0] orgid = c.get('id') #read all networks networks = meraki.getnetworklist(apikey, orgid, suppressprint=True) for net in networks: netID = net.get('id') netName = net.get('name') print('*' * 80) print('NETWORK NAME {:20} ID {}'.format(netName, netID)) deviceList = meraki.getnetworkdevices(apikey, netID, suppressprint=True) for device in deviceList: if "MX" in device.get('model'): d = 'SECURITY POLICIES FOR DEVICE {} SERIAL {}'.format( device.get('model'), device.get('serial')) print('*' * 80) print(d) print('*' * 80) g = meraki.getmxl3fwrules(apikey, netID, suppressprint=True)
import login (api_key, api_id) = (login.api_key, login.org_id) except ImportError: api_key = input('Enter your Dashboard API key: ') api_id = input('Enter your organization ID: ') today = datetime.date.today() csv_file = open(login.org_name + '_' + str(today) + '.csv', 'w', encoding='utf-8') fieldnames = ['Network_Name', 'SSID_Name', 'PSK'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames, restval='') writer.writeheader() current_networks = meraki.getnetworklist(api_key, api_id, suppressprint=True) for network in current_networks: api_netid = network['id'] ssids = meraki.getssids(api_key, api_netid, suppressprint=True) if str(ssids) == 'None': pass else: ssid_num = len(ssids) for num in range(0, ssid_num - 1): if ssids[num]['name'].startswith("Unconfigured SSID"): pass elif ssids[num]['authMode'] == 'psk': print(network['name'] + ',' + ssids[num]['name'] + ',' +
) # Defines arguments passed on the command line when running program suppressprint = True if args.v: suppressprint = False apikey = args.apiKey orgid = get_org_id(apikey, args.orgName, suppressprint) file = "%s.yml" % args.orgName # set the filename from the network name config["Organization"]["Name"] = args.orgName config["Organization"]["ID"] = orgid admins(apikey, orgid, suppressprint) mx_vpn_fw_rules(apikey, orgid, suppressprint) snmp_settings(apikey, orgid, suppressprint) non_meraki_vpn_peers(apikey, orgid, suppressprint) myNetworks = meraki.getnetworklist(apikey, orgid, None, suppressprint) for row in myNetworks: # Iterate through the networks in the org tags = row['tags'] if tags == None: tags = "" networkType = row['type'] if networkType == 'combined': # Combined is not valid to upload! networkType = 'wireless switch appliance phone' if networkType == 'systems manager': # We don't care about MDM networks continue print("Processing network " + row['name']) network = { "name": row["name"], "networkType": networkType, "tags": tags, "timeZone": row["timeZone"]
def main(argv): # Set default values for command line arguments api_key = org_id = arg_template = arg_tag = arg_switch = 'null' # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:o:t:n:s:') except getopt.GetoptError: # printhelp() sys.exit(2) for opt, arg in opts: if opt == '-h': printhelp() sys.exit() elif opt == '-k': api_key = arg elif opt == '-o': org_id = arg elif opt == '-t': arg_template = arg elif opt == '-n': arg_tag = arg elif opt == '-s': arg_switch = arg # Check if all parameters are required parameters have been given if api_key == 'null' or org_id == 'null' or arg_template == 'null' or arg_tag == 'null': printhelp() sys.exit(2) '''if arg_switch not in ('null', 'True', 'true', 'False', 'false'): printhelp() sys.exit(2)''' # Find all networks matching input tag networks = meraki.getnetworklist(api_key, org_id) time.sleep(1) tagged_networks = [ network for network in networks if network['tags'] and arg_tag in network['tags'] ] # Find all templates templates = meraki.gettemplates(api_key, org_id) time.sleep(1) template_ids = [template['id'] for template in templates] template_names = [template['name'] for template in templates] target_template_id = template_ids[template_names.index(arg_template)] # Tally up number of networks that are either unbound or currently bound to other templates unbound_count = 0 for network in tagged_networks: if 'configTemplateId' in network: index = template_ids.index(network['configTemplateId']) if 'count' in templates[index]: templates[index]['count'] += 1 else: templates[index]['count'] = 1 else: unbound_count += 1 # Confirm with user number of networks to be updated print('Found a grand total of {0} networks with the tag {1}:'.format( len(tagged_networks), arg_tag)) if unbound_count > 0: print('{0} networks are currently unbound, not bound to any template'. format(unbound_count)) for template in templates: if 'count' in template and template['count'] > 0: print('{0} networks are currently bound to template {1}'.format( template['count'], template['name'])) continue_run = input( 'Continue to update by binding all {0} networks to the {1} template? (Y/N) ' .format(len(tagged_networks), arg_template)) # Update and bind networks to template for network in tagged_networks: net_id = network['id'] net_name = network['name'] old_vlans = meraki.getvlans(api_key, net_id) time.sleep(1) old_vlan_ids = [vlan['id'] for vlan in old_vlans] if 'configTemplateId' in network: template_name = template_names[template_ids.index( network['configTemplateId'])] print('Unbinding network {0} from current template {1}'.format( net_name, template_name)) meraki.unbindfromtemplate(api_key, net_id) time.sleep(1) print('Binding network {0} to target template {1}'.format( net_name, arg_template)) if arg_switch in ('True', 'true'): meraki.bindtotemplate(api_key, net_id, target_template_id, True) time.sleep(1) else: meraki.bindtotemplate(api_key, net_id, target_template_id, False) time.sleep(1) new_vlans = meraki.getvlans(api_key, net_id) time.sleep(1) for new_vlan in new_vlans: vlan_id = new_vlan['id'] old_vlan = old_vlans[old_vlan_ids.index(vlan_id)] if new_vlan['subnet'] != old_vlan['subnet'] or new_vlan[ 'applianceIp'] != old_vlan['applianceIp']: meraki.updatevlan(api_key, net_id, vlan_id, subnet=old_vlan['subnet'], mxip=old_vlan['applianceIp']) time.sleep(1)
def get_networks(): networks = meraki.getnetworklist(config['api_key'], config['org_id'], suppressprint=True) return networks
def get_route_by_subnet(apikey, networkid, subnet): routes = meraki.getstaticroutes(apikey, networkid) for r in routes: if r['subnet'] == subnet: return r return None apikey = os.getenv("MERAKI_API_KEY", None) if not apikey: print("Please make sure you have MERAKI_API_KEY environment variable set") sys.exit(1) myOrgs = meraki.myorgaccess(apikey) print(myOrgs) nets = meraki.getnetworklist(apikey, ORG_ID) print('nets available: ') for n in nets: print(n['name']) print("routes available at hub1") h1routes = meraki.getstaticroutes(apikey, NETWORK_MAP['Hub 1']) for r in h1routes: print(r) print("routes available at hub2") h1routes = meraki.getstaticroutes(apikey, NETWORK_MAP['Hub 2']) for r in h1routes: print(r) interesting_route = get_route_by_subnet(apikey, NETWORK_MAP['Hub 2'],
index = org_names.index('Public API Lab') my_org = orgs[index]['id'] ##### DO NOT MODIFY ##### # 1. Create a network ######################### ##### START EDITING ##### my_name = 'First Last' my_tags = ['Tag1', 'Tag2', 'Tag3'] my_time = 'US/Pacific' ###### END EDITING ###### ######################### # Get the current list of networks current_networks = meraki.getnetworklist(my_key, my_org) # Get the current networks' names network_names = [network['name'] for network in current_networks] # Was my_name changed from default 'First Last'? if my_name == 'First Last': sys.exit('Part 1: please edit your name\n') # Have tags been added? elif my_tags == '': sys.exit(('Part 1: please add some tags\n')) # Does the network already exist? elif my_name in network_names: my_netid = current_networks[network_names.index(my_name)]['id'] print('Part 1: the network {0} already exists with ID {1}\n'.format( my_name, my_netid))
return "nada" x = '1' while (x == '1'): apidata = m.myorgaccess(apikey, suppressprint=True) # id|name|samlConsumerUrl|samlConsumerUrls selectedOrg = explore_next(apikey, apidata, ['id', 'name'], "Organization", "id") print( "please select:\n1: Get List of Networks\n2: Get Licenses\n3: Get Inventory\n4: Get Templates\n5: Get SNMP Settings" ) user_input = input("##: ") if user_input == '1': apidata = m.getnetworklist(apikey, selectedOrg, suppressprint=True) #configTemplateId|id|name|organizationId|tags|timeZone|type selectedNetwork = explore_next( 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("##: ")
net_type_cap = [] cap_serial = [] cap_counter = [] try: logging.info('start time') for org in meraki.myorgaccess(KEY): if org.get('name') == 'CNB - Camera' and org.get('id') == '597852850533433525': continue org_names.append(org.get('name')) org_ids.append(org.get('id')) org_names_ids = sorted(list(zip(org_names, org_ids))) for single in org_names_ids: networks = meraki.getnetworklist(KEY, single[1]) for network in networks: if 'ADMINISTRAÇÃO' in network.get('name'): set_adm = [network.get('organizationId'), network.get('name'), network.get('id')] net_ids_adm.append(set_adm) elif 'CAPTIVE PORTAL WIFI' in network.get('name'): set_captive = [network.get('organizationId'), network.get('name'), network.get('id')] net_ids_captive.append(set_captive) else: continue 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)
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))
def insert_ssid_l3fw_rules(api_key, api_id, ssid_name): api_key = api_key api_id = api_id ssid_name = ssid_name fwrules=[] with open(input_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: csv_comment = row['comment'] csv_policy = row['policy'] csv_protocol = row['protocol'] csv_destPort = row['destPort'] csv_destCidr = row['destCidr'] fwrules_data = [{'comment': csv_comment, 'policy': csv_policy, 'protocol': csv_protocol, 'destPort': csv_destPort, 'destCidr': csv_destCidr}] print(fwrules_data[0]) fwrules.append(fwrules_data[0]) resp=input('Do you want to insert the above rules? [y|n]') while resp in ('y', 'n'): if resp == 'y': resp_mode=input('Intert Rules at top? or Above the default rule? or interactive mode for each matched ssid? [t|b|i] ') current_networks = meraki.getnetworklist(api_key, api_id,suppressprint=True) for network in current_networks: api_netid = network['id'] ssids = meraki.getssids(api_key, api_netid, suppressprint=True) if str(ssids) == 'None': pass else: ssid_num = len(ssids) for num in range(0,ssid_num-1): if ssids[num]['name'].startswith("Unconfigured SSID"): pass elif ssids[num]['name'].endswith(ssid_name): print(network['name']+','+network['id']+','+ssids[num]['name']) print(' ') g_response=meraki.getssidl3fwrules(api_key, network['id'], ssids[num], suppressprint=False) for rule_num in range(0,len(g_response)-2): print(rule_num+1, g_response[rule_num]) print(' ') if resp_mode == 't': for r_num in range(0,len(fwrules)): g_response.insert(0, fwrules[r_num]) elif resp_mode == 'b': for r_num in range(0,len(fwrules)): g_response.insert(len(g_response)-2, fwrules[r_num]) elif resp_mode == 'i': is_valid=0 while not is_valid : try : insert_num = int(input('Enter the rule number of the rule you would like to insert BELOW: ')) is_valid = 1 # set it to 1 to validate input and to terminate the while..not loop except ValueError: print ("'%s' Enter the rule number." % e.args[0].split(": ")[1]) for r_num in range(0,len(fwrules)): g_response.insert(insert_num, fwrules[r_num]) else: print('Please start again!') break fwrules=g_response[:-2] print(fwrules) u_response=meraki.updatessidl3fwrules(api_key, network['id'], ssids[num], fwrules, allowlan=None, suppressprint=False) print(u_response) print('') for rule_num in range(0,len(u_response)): print(rule_num+1, u_response[rule_num]) print('') break else: break