Struggling with L3 ACL export! Dict not a list?

uncletootall
Conversationalist

Struggling with L3 ACL export! Dict not a list?

Hi All 

 

I found a script online which isn't working so I'm trying to create my own following the python guide here... please help!

 

 

 

response = dashboard.appliance.getNetworkApplianceFirewallL3FirewallRules(
    network_id
)

 

 

 
I get my response but that is currently a dict and thus I cannot seem to go through with a loop.... I'm a bit of a python noob. Should I be expecting a list?
 
This is was I found online that also doesn't work

 

 

 

# Prints READ_ME help message for user to read
def print_help():
    lines = READ_ME.split('\n')
    for line in lines:
        print('# {0}'.format(line))


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 and os.getenv('MERAKI_DASHBOARD_API_KEY') == None) or net_id == None:
        print_help()
        sys.exit(2)

    # Set the CSV output file and write the header row
    time_now = f'{datetime.now():%Y-%m-%d_%H-%M-%S}'
    file_name = f'mx_l3fw_rules__{time_now}.csv'
    output_file = open(file_name, 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)

    # Dashboard API library class
    m = meraki.DashboardAPI(api_key=api_key, log_file_prefix=__file__[:-3])

    # Read configuration of MX L3 firewall rules
    fw_rules = m.appliance.getNetworkApplianceFirewallL3FirewallRules(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(f'Export completed to file {file_name}')


if __name__ == '__main__':
    main(sys.argv[1:])

 

 

3 Replies 3
sungod
Kind of a big deal

Just quick as I am heading out.

 

Use a recent Python, 3.8 or newer.

 

Start with the easiest way so that you have a working script to build on

 

To iterate through an array of dictionaries...

 

responses = some_api_call(blah, blah)

for response in responses:
    print(response)

 

 

 You can reference an item in a dictionary like this...

 

responses = some_api_call(blah, blah)

for response in responses:
    print(response['itemname'])

 

Look online to see how to print multiple things in a single print call, or concatenate things into a longer string, or turn numbers into strings, etc. etc

 

 

sungod
Kind of a big deal

I just looked at this API call, the example snippet below shows how to output the result as a tab-separated list, if you want commas instead of tabs, just edit to substitute "," for "\t".

 

But be careful, some fields can contain commas, you'd need to add extra quotes to 'hide' them from whatever will read the output. This is why I always use tabs 😀

 

 

response = theapicall(net_id)

for rule in response['rules']:
    print(f"{rule['comment']}\t{rule['policy']}\t{rule['protocol']}\t{rule['destPort']}\t{rule['destCidr']}\t{rule['srcPort']}\t{rule['srcCidr']}\t{rule['syslogEnabled']}")

 

 

 

In your code, you'll probably need to check you only make the call on networks that have an MX on them, otherwise you might get an error rather than an empty ruleset.

 

If you haven't already installed it, use the Meraki Python library, it will make things easier, there are some example scripts on the corresponding github site

 

To install the library...

pip3 install meraki

 

Home page: https://pypi.org/project/meraki/

Github: https://github.com/meraki/dashboard-api-python

 

uncletootall
Conversationalist

Ah I'm close! Now I need to play around with that output and get it into a .CSV! Thay gave me all the ACLs formatted neatly. 

 

Bit annoying it's giving me loads of OBJ objects and now the actual cidr.. 😞

 

Thank you!

Get notified when there are additional replies to this discussion.