def main(argv): # Set default values for command line arguments api_key = net_id = None # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:n:') 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 == '-n': net_id = arg # Check if all required parameters have been input if api_key == None or net_id == None: print_help() sys.exit(2) # Set the CSV output file and write the header row timenow = '{:%Y%m%d_%H%M%S}'.format(datetime.now()) filename = 'mx_l3fw_rules_{0}.csv'.format(timenow) output_file = open(filename, mode='w', newline='\n') field_names = ['policy','protocol','srcCidr','srcPort','destCidr','destPort','comment','logging'] csv_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) csv_writer.writerow(field_names) # Read Dashboard configuration of MX L3 firewall rules fw_rules = meraki.getmxl3fwrules(api_key, net_id) # Loop through each firewall rule and write to CSV for rule in fw_rules: csv_row = [rule['policy'], rule['protocol'], rule['srcCidr'], rule['srcPort'], rule['destCidr'], rule['destPort'], rule['comment'], rule['syslogEnabled']] csv_writer.writerow(csv_row) output_file.close() print('Export completed to file {0}'.format(filename))
def main(netid, argfile): with open(os.path.join(os.pardir, "api/api_credentials.json"), "r") as creds: # Reads the api_credentials.json file for authentication keys = json.load(creds) # Defines the plain text API key generated in the Meraki portal apikey = keys[0]["apikey"] # Set default values for command line arguments netid = netid # Set the CSV output file and write the header row timenow = '{:%Y%m%d_%H%M%S}'.format(datetime.now()) filename = 'mx_l3fw_rules_{0}.csv'.format(timenow) output_file = open(os.path.join(os.pardir, 'data/') + netid + '.csv', mode='w') field_names = [ 'policy', 'protocol', 'srcCidr', 'srcPort', 'destCidr', 'destPort', 'comment', 'logging' ] csv_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) csv_writer.writerow(field_names) # Read Dashboard configuration of MX L3 firewall rules fw_rules = meraki.getmxl3fwrules(apikey, netid) # Loop through each firewall rule and write to CSV for rule in fw_rules: csv_row = [ rule['policy'], rule['protocol'], rule['srcCidr'], rule['srcPort'], rule['destCidr'], rule['destPort'], rule['comment'], rule['syslogEnabled'] ] csv_writer.writerow(csv_row) output_file.close() print('Export completed to file {0}'.format(filename))
def main(argv): # Set default values for command line arguments api_key = net_id = arg_file = arg_mode = None # Get command line arguments try: opts, args = getopt.getopt(argv, 'hk:n:f: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 == '-n': net_id = arg elif opt == '-f': arg_file = arg elif opt == '-m': arg_mode = arg # Check if all required parameters have been input if api_key == None or net_id == None or arg_file == None: print_help() sys.exit(2) # Assign default mode to "simulate" unless "commit" specified if arg_mode != 'commit': arg_mode = 'simulate' # Read CSV input file, and skip header row input_file = open(arg_file) csv_reader = csv.reader(input_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) next(csv_reader, None) logger.info('Reading file {0}'.format(arg_file)) # Loop through each firewall rule from CSV file and build PUT data fw_rules = [] for row in csv_reader: rule = dict({ 'policy': row[0], 'protocol': row[1], 'srcCidr': row[2], 'srcPort': row[3], 'destCidr': row[4], 'destPort': row[5], 'comment': row[6], 'syslogEnabled': (row[7] == True or row[7] == 'True' or row[7] == 'true') }) fw_rules.append(rule) old_rules = list(fw_rules) logger.info('Processed all {0} rules of file {1}'.format( len(fw_rules), arg_file)) # Check if last (default) rule exists, and if so, remove and check for default logging default_rule_exists = False default_logging = False last_rule = { 'comment': 'Default rule', 'policy': 'allow', 'protocol': 'Any', 'srcPort': 'Any', 'srcCidr': 'Any', 'destPort': 'Any', 'destCidr': 'Any' } if all(item in fw_rules[-1].items() for item in last_rule.items()): default_rule_exists = True default_logging = (fw_rules.pop()['syslogEnabled'] == True) # Update MX L3 firewall rules if arg_mode == 'commit': meraki.updatemxl3fwrules(api_key, net_id, fw_rules, default_logging) logger.info( 'Attempting update of firewall rules to network {0}'.format( net_id)) # Confirm whether changes were successfully made new_rules = meraki.getmxl3fwrules(api_key, net_id) if default_rule_exists and new_rules[:-1] == old_rules[:-1]: logger.info('Update successful!') elif not (default_rule_exists) and new_rules[:-1] == old_rules: logger.info('Update successful!') else: logger.error('Uh oh, something went wrong...') else: logger.info( 'Simulating update of firewall rules to network {0}'.format( net_id))
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) print(g)
import csv # if the meraki library is installed via pip, use the import line below: from meraki import meraki api_key = 'insert api key here' net_id = 'insert net id here' org_id = 'insert org id here' # Set the CSV output file and write a header row output_file = open('mx_fw_rules.csv', mode='w') csv_writer = csv.writer(output_file, escapechar=' ', quoting=csv.QUOTE_NONE) header_row_text = "Comment, Policy, Protocol, Source Port, Source CIDR, Destination Port, Destination CIDR, Syslog Enabled ?" csv_writer.writerow([header_row_text]) # use the getmxl3fwrules function in the meraki dashboard api library fw_rules = meraki.getmxl3fwrules(api_key, net_id) print("^^^ Full output:", fw_rules) # loop through each firewall rule, create a csv row and write to file for rule in fw_rules: print("@@@ Print each rule from the GET response:", str(rule)) csv_row = "{0},{1},{2},{3},{4},{5},{6},{7}".format( rule['comment'], rule['policy'], rule['protocol'], rule['srcPort'], rule['srcCidr'], rule['destPort'], rule['destCidr'], rule['syslogEnabled']) print("### Writing this row to CSV:", csv_row) csv_writer.writerow([csv_row]) output_file.close()
def main(netid, argfile, argmode): with open(os.path.join(os.pardir, "api/api_credentials.json"), "r") as creds: # Reads the api_credentials.json file for authentication keys = json.load(creds) # Defines the plain text API key generated in the Meraki portal apikey = keys[0]["apikey"] # Set default values for command line arguments netid = netid argfile = argfile argmode = argmode # Assign default mode to "check" unless "commit" specified if argmode != 'commit': argmode = 'check' fw_rules = [] # Read CSV input file, and skip header row input_file = open(argfile) csv_reader = csv.reader(input_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) next(csv_reader, None) logger.info('Reading file {0}'.format(argfile)) # Loop through each firewall rule from CSV file and build PUT data for row in csv_reader: rule = dict({ 'policy': row[0], 'protocol': row[1], 'srcCidr': row[2], 'srcPort': row[3], 'destCidr': row[4], 'destPort': row[5], 'comment': row[6], 'syslogEnabled': (row[7] == True or row[7] == 'True' or row[7] == 'true') }) fw_rules.append(rule) print(fw_rules) old_rules = list(fw_rules) logger.info('Processed all {0} rules of file {1}'.format( len(fw_rules), argfile)) # Check if last (default) rule exists, and if so, remove and check for default logging default_rule_exists = False default_logging = False last_rule = { 'comment': 'Default rule', 'policy': 'allow', 'protocol': 'Any', 'srcPort': 'Any', 'srcCidr': 'Any', 'destPort': 'Any', 'destCidr': 'Any' } if all(item in fw_rules[-1].items() for item in last_rule.items()): default_rule_exists = True default_logging = (fw_rules.pop()['syslogEnabled'] == True) # Update MX L3 firewall rules if argmode == 'commit': meraki.updatemxl3fwrules(apikey, netid, fw_rules, default_logging) logger.info( 'Attempting update of firewall rules to network {0}'.format(netid)) # Confirm whether changes were successfully made new_rules = meraki.getmxl3fwrules(apikey, netid) if default_rule_exists and new_rules[:-1] == old_rules[:-1]: logger.info('Update successful!') elif not (default_rule_exists) and new_rules[:-1] == old_rules: logger.info('Update successful!') else: logger.error('Uh oh, something went wrong...') else: logger.info( 'Simulating update of firewall rules to network {0}'.format(netid))
print("Updating rules for Network ID: " + theNetworkid + " named: ", theNetwork["name"], "...") continueAnswer = "y" #Comment line below if you wish to skip confirmation for each Network continueAnswer = input( "Continue? yes, no or skip(y/n/s): ").lower().strip()[:1] if continueAnswer == "n": print("Bye!") sys.exit(1) elif continueAnswer == "s": print("Skipping Network ID: " + theNetworkid + " named: ", theNetwork["name"], "...") continue #get the rules theMXL3FirewallRules = meraki.getmxl3fwrules(config.meraki_api_key, theNetworkid, True) #retrieving the syslog servers to know which template to use theSysLogServers = getsyslogservers(config.meraki_api_key, theNetworkid, True) #print("Syslog Servers: ", theSysLogServers) # compose the new rule to add in the right format using the corresponding Dict template if theSysLogServers == []: theRuleToAddDict = templateRuleDictNoSyslog else: theRuleToAddDict = templateRuleDict theRuleToAddDict["comment"] = theRuleComment theRuleToAddDict["destCidr"] = theRuleIPs #removing any marked as "Default rule" to avoid duplicates
def mx_l3_fw_rules( apikey, networkid, suppressprint): #Retrieves the Layer 3 firewall rules on the MX myRules = meraki.getmxl3fwrules(apikey, networkid, suppressprint)[0:-1] network["L3-Firewall-Rules"] = myRules print("Got Layer 3 firewall rules")
import csv # if the meraki library is installed via pip, use the import line below: from meraki import meraki api_key = 'insert api key here' net_id = 'insert net id here' org_id = 'insert org id here' # Set the CSV output file and write a header row output_file = open('mx_fw_rules.csv', mode='w') csv_writer = csv.writer(output_file, escapechar=' ', quoting=csv.QUOTE_NONE) header_row_text = "Comment, Policy, Protocol, Source Port, Source CIDR, Destination Port, Destination CIDR, Syslog Enabled ?" csv_writer.writerow([header_row_text]) # use the getmxl3fwrules function in the meraki dashboard api library fw_rules = meraki.getmxl3fwrules(api_key,net_id) print("^^^ Full output:", fw_rules) # loop through each firewall rule, create a csv row and write to file for rule in fw_rules: print("@@@ Print each rule from the GET response:", str(rule)) csv_row = "{0},{1},{2},{3},{4},{5},{6},{7}".format(rule['comment'], rule['policy'], rule['protocol'], rule['srcPort'], rule['srcCidr'], rule['destPort'], rule['destCidr'], rule['syslogEnabled']) print("### Writing this row to CSV:", csv_row) csv_writer.writerow([csv_row]) output_file.close()