Browse Source

Modernize for Python 3.

Joe Clarke 2 years ago
parent
commit
ff33e024fd
2 changed files with 57 additions and 59 deletions
  1. 19 20
      example_org.yaml
  2. 38 39
      setup-meraki-nets.py

+ 19 - 20
example_org.yaml

@@ -1,21 +1,20 @@
-organization:                     "My Organization"
-api_key:                          "1234567890abcdef"
+organization: "My Organization"
+api_key: "1234567890abcdef"
 networks:
-    - Example Network:
-        address:                  "123 Any Street, Any City, Any State USA"
-        timezone:                 "America/Los_Angeles"
-        devices:
-            - 1234-1234-1234:
-                name:               rtr-mtg
-                location:           Meeting Room
-            - 5678-5678-5678:
-                name:               ap-mtg
-                location:           Meeting Room
-        ssids:
-            - SSID 1:
-                name:             examplewifi
-                enabled:          True
-                auth_mode:        psk
-                encryption_mode:  wpa
-                psk:              Sup3Rs3cr#t
-    
+  Example Network:
+    address: "123 Any Street, Any City, Any State USA"
+    timezone: "America/Los_Angeles"
+    devices:
+      1234-1234-1234:
+        name: rtr-mtg
+        location: Meeting Room
+      5678-5678-5678:
+        name: ap-mtg
+        location: Meeting Room
+    ssids:
+      SSID 1:
+        name: examplewifi
+        enabled: True
+        auth_mode: psk
+        encryption_mode: wpa
+        psk: Sup3Rs3cr#t

+ 38 - 39
setup-meraki-nets.py

@@ -34,6 +34,11 @@ import os
 from colorama import Fore, Style
 import colorama
 
+try:
+    from yaml import CLoader as Loader
+except ImportError:
+    from yaml import Loader
+
 BANNER = "[{}] **********************************************************"
 
 
@@ -51,7 +56,7 @@ def main():
 
     print(BANNER.format("Loading config file"))
     with open(args.config, "r") as c:
-        config = yaml.load(c)
+        config = yaml.load(c, Loader=Loader)
     print("{}ok{}\n".format(Fore.GREEN, Style.RESET_ALL))
 
     for key in ["api_key", "organization", "networks"]:
@@ -80,10 +85,9 @@ def main():
     if args.networks is not None:
         configure_nets = args.networks.split(",")
 
-    for net in config["networks"]:
+    for nname, network in config["networks"].items():
         nerrors = 0
         net_obj = None
-        nname = list(net.keys())[0]
         print(BANNER.format("Configuring network {}".format(nname)))
         if configure_nets is not None and nname not in configure_nets:
             print("{}skipping (not in specified network list){}".format(Fore.BLUE, Style.RESET_ALL))
@@ -91,7 +95,7 @@ def main():
 
         validn = True
         for key in ["address", "timezone"]:
-            if key not in net[nname]:
+            if key not in network:
                 print("{}Invalid network config for {}: {} is missing!{}".format(Fore.RED, nname, key, Style.RESET_ALL))
                 errors += 1
                 validn = False
@@ -106,10 +110,10 @@ def main():
                 break
 
         if net_obj is None:
-            nargs = {"timezone": net[nname]["timezone"]}
-            if "copy_from_network" in net[nname]:
+            nargs = {"timezone": network["timezone"]}
+            if "copy_from_network" in network:
                 for n in nets:
-                    if n.get("name") == net[nname]["copy_from_network"]:
+                    if n.get("name") == network["copy_from_network"]:
                         nargs["copy_from_network_id"] = n.get("id")
                         break
             net_obj = org.create_network(nname, **nargs)
@@ -119,10 +123,9 @@ def main():
             errors += 1
             continue
 
-        if "devices" in net[nname]:
-            for dev in net[nname]["devices"]:
-                serial = list(dev.keys())[0]
-                if "name" not in dev[serial]:
+        if "devices" in network:
+            for serial, dev in network["devices"].items():
+                if "name" not in dev:
                     print("{}Invalid device {}: name is missing!{}".format(Fore.RED, serial, Style.RESET_ALL))
                     nerrors += 1
                     continue
@@ -183,10 +186,10 @@ def main():
                         dev_obj = Device(key=config["api_key"], id=inv_dev[0]["serial"], net=net_obj)
                         print("{}ok: {} is in network{}".format(Fore.GREEN, inv_dev[0]["serial"], Style.RESET_ALL))
 
-                    dev_location = net[nname]["address"]
-                    dev_name = dev[serial]["name"]
-                    if "location" in dev[serial]:
-                        dev_location += "\n" + dev[serial]["location"]
+                    dev_location = network["address"]
+                    dev_name = dev["name"]
+                    if "location" in dev:
+                        dev_location += "\n" + dev["location"]
                     dev_obj.update_device(name=dev_name, address=dev_location, move_map_marker=True)
                     print("{}update: updated {} name and location{}".format(Fore.YELLOW, inv_dev[0]["serial"], Style.RESET_ALL))
 
@@ -194,7 +197,7 @@ def main():
                     print("{}Error finding {} in inventory!{}".format(Fore.RED, serial, Style.RESET_ALL))
                     nerrors += 1
 
-        if "vlans" in net[nname]:
+        if "vlans" in network:
             # Ugh.  There is no API to enable VLANs yet.  So it's best to
             # make this a manual step.  We could interact over the web, but
             # then we'd need to ask for a real user's credentials.
@@ -202,7 +205,7 @@ def main():
             # If we copied from an existing network, then we assume that
             # network has VLANs enabled.  If not, this will fail.
             #
-            if "copy_from_network" not in net[nname]:
+            if "copy_from_network" not in network:
                 print("\n")
                 input(
                     '!!! Enable VLANs for network "{}" manually in the dashboard (under Security appliance > Addressing & VLANs), then hit \
@@ -211,21 +214,20 @@ def main():
                     )
                 )
                 print("")
-            for vlan in net[nname]["vlans"]:
-                vname = list(vlan.keys())[0]
+            for vname, vlan in network["vlans"].items():
                 done_msg = ""
-                if int(vlan[vname]["id"]) != 1:
-                    vlan_obj = net_obj.create_vlan(vname, vlan[vname]["id"], vlan[vname]["subnet"], vlan[vname]["appliance_ip"])
+                if int(vlan["id"]) != 1:
+                    vlan_obj = net_obj.create_vlan(vname, vlan["id"], vlan["subnet"], vlan["appliance_ip"])
                     done_msg = "{}update: created VLAN {} (id={}, subnet={}, appliance_ip={}){}".format(
-                        Fore.YELLOW, vname, vlan[vname]["id"], vlan[vname]["subnet"], vlan[vname]["appliance_ip"], Style.RESET_ALL
+                        Fore.YELLOW, vname, vlan["id"], vlan["subnet"], vlan["appliance_ip"], Style.RESET_ALL
                     )
                 else:
                     vlan_obj = Vlan(key=config["api_key"], id=1, net=net_obj)
-                    done_msg = "{}ok: VLAN with ID {} exists{}".format(Fore.GREEN, vlan[vname]["id"], Style.RESET_ALL)
+                    done_msg = "{}ok: VLAN with ID {} exists{}".format(Fore.GREEN, vlan["id"], Style.RESET_ALL)
                 if vlan_obj is None:
                     print(
                         "{}Error creating VLAN {} (id={}, subnet={}, appliance_ip={})!{}".format(
-                            Fore.RED, vname, vlan[vname]["id"], vlan[vname]["subnet"], vlan[vname]["appliance_ip"], Style.RESET_ALL
+                            Fore.RED, vname, vlan["id"], vlan["subnet"], vlan["appliance_ip"], Style.RESET_ALL
                         )
                     )
                     nerrors += 1
@@ -233,8 +235,8 @@ def main():
                 print(done_msg)
                 vargs = {}
                 for key in ["reserved_ip_ranges", "fixed_ip_assignments", "dns_nameservers"]:
-                    if key in vlan[vname]:
-                        vargs[key] = vlan[vname][key]
+                    if key in vlan:
+                        vargs[key] = vlan[key]
                 res = vlan_obj.update_vlan(**vargs)
                 vargs_str = ", ".join(["{}={}".format(k, v) for k, v in vargs.items()])
                 if not res:
@@ -243,19 +245,18 @@ def main():
                 else:
                     print("{}update: Update VLAN {} ({}){}".format(Fore.YELLOW, vname, vargs_str, Style.RESET_ALL))
 
-        if "ssids" in net[nname]:
-            if len(net[nname]["ssids"]) > 15:
+        if "ssids" in network:
+            if len(network["ssids"]) > 15:
                 print("{}Only fifteen SSIDs are allowed per network!{}".format(Fore.RED, Style.RESET_ALL))
                 nerrors += 1
             else:
                 si = 0
-                for ssid in net[nname]["ssids"]:
-                    sname = list(ssid.keys())[0]
+                for sname, ssid in network["ssids"].items():
                     ssid_obj = SSID(key=config["api_key"], id=si, name=sname, net=net_obj)
                     sargs = {}
                     for key in ["name", "enabled", "auth_mode", "encryption_mode", "psk", "ip_assignment_mode"]:
-                        if key in ssid[sname]:
-                            sargs[key] = ssid[sname][key]
+                        if key in ssid:
+                            sargs[key] = ssid[key]
                     res = ssid_obj.update_ssid(**sargs)
                     sargs_str = ", ".join(["{}={}".format(k, v) for k, v in sargs.items()])
                     if not res:
@@ -265,17 +266,15 @@ def main():
                         print("{}update: Update SSID {} ({}){}".format(Fore.YELLOW, sname, sargs_str, Style.RESET_ALL))
                     si += 1
 
-        if "switches" in net[nname]:
-            for switch in net[nname]["switches"]:
-                serial = list(switch.keys())[0]
+        if "switches" in network:
+            for serial, switch in network["switches"].items():
                 dev_obj = Device(key=config["api_key"], id=serial, net=net_obj)
                 if not dev_obj.realize():
                     print("{}Device {} is not in network {}{}".format(Fore.RED, serial, net_obj.get("name"), Style.RESET_ALL))
                     nerrors += 1
                     continue
 
-                for switchport in switch[serial]:
-                    port_range = list(switchport.keys())[0]
+                for port_range, switchport in switch.items():
                     ports = []
                     if isinstance(port_range, int):
                         port_obj = SwitchPort(key=config["api_key"], id=port_range, dev=dev_obj)
@@ -319,8 +318,8 @@ def main():
                     for port in ports:
                         pargs = {}
                         for key in ["name", "tags", "enabled", "type", "vlan", "voice_vlan", "allowed_vlans", "poe_enabled"]:
-                            if key in switchport[port_range]:
-                                pargs[key] = switchport[port_range][key]
+                            if key in switchport:
+                                pargs[key] = switchport[key]
                         res = port.update_switchport(**pargs)
                         pargs_str = ", ".join(["{}={}".format(k, v) for k, v in pargs.items()])
                         if not res: