Exemplo n.º 1
0
def main():
    """
    Execution begins here.
    """

    # Load the camera settings from JSON file
    with open("camera_settings.json", "r") as handle:
        settings = json.load(handle)

    # Iterate over the cameras collected
    for sn, body in settings.items():

        # Collect the current settings
        url = f"devices/{sn}/camera/qualityAndRetentionSettings"
        current = req(url).json()

        # Print the current quality and retention settings
        print(f"\nCurrent settings for camera {sn}")
        print(json.dumps(current, indent=2))

        # Issue a PUT request to update the settings based on the
        # JSON data read from the input file
        updated = req(url, method="put", json=body).json()

        # Print the newly updated quality and retention settings
        print(f"\nUpdated settings for camera {sn}")
        print(json.dumps(updated, indent=2))
Exemplo n.º 2
0
def main(org_name, net_name):
    """
    Execution begins here.
    """

    # Find the network ID for our reserved instance (or personal org)
    net_id = get_network_id(net_name, org_name)

    with open("add_portals.json", "r") as handle:
        portals = json.load(handle)

    for ssid_number, body in portals.items():

        # Assemble the SSID base URL and the HTTP PUT request payload
        ssid_base = f"networks/{net_id}/ssids/{ssid_number}"

        # Issue the PUT request to update the SSID general parameters
        print(f"Updating SSID {ssid_number} for {body['ssid_body']['name']}")
        update_ssid = req(ssid_base, method="put", json=body["ssid_body"])

        # Debugging statement to check the updated SSID information
        # print(json.dumps(update_ssid.json(), indent=2))

        # Issue the PUT request to update the splash page parameters if they exist
        if body["splash_body"]:
            print(
                f"Update SSID {ssid_number} excap to {body['splash_body']['splashUrl']}"
            )
            update_splash = req(f"{ssid_base}/splashSettings",
                                method="put",
                                json=body["splash_body"])
Exemplo n.º 3
0
def main(argv):
    """
    Execution begins here.
    """

    # Ensure there are exactly 3 arguments for the script name,
    # SSID number, and off/on state
    if len(argv) != 3:
        print(f"usage: python {argv[0]} <ssid#> <0 (off) -OR- 1 (on)>")
        sys.exit(1)

    # Convert inputs away from strings; guarantees they are valid because
    # if type conversion fails, errors are raised and program crashes
    ssid_number = int(argv[1])
    ssid_enable = bool(int(argv[2]))
    print(f"SSID {ssid_number} enable state being set to {ssid_enable}")

    # Find the DevNet network ID within the DevNet organization.
    # These are default arguments when left unspecified
    devnet_network = find_network()

    # Perform an HTTP PUT to update an existing SSID by number by changing
    # the enabled state. HTTP PUT in most REST APIs is idempotent so
    # if the state doesn't change, Meraki won't do anything.
    put_resp = req(
        f"networks/{devnet_network}/ssids/{ssid_number}",
        method="put",
        json={"enabled": ssid_enable},
    )
    put_resp_json = put_resp.json()

    # Debugging line; pretty-print JSON to see structure
    # import json; print(json.dumps(put_resp_json, indent=2))

    print(f"SSID enabled state is currently {put_resp_json['enabled']}")
Exemplo n.º 4
0
def main(sn):
    """
    Execution begins here.
    """

    # Query the following URL endpoints:
    #  live: exact point in time
    #  recent: past 1 minute
    #  overview: past 1 hour
    for resource in ["live", "recent", "overview"]:

        # Issue the HTTP GET request
        analytics = req(f"devices/{sn}/camera/analytics/{resource}").json()

        # Print the analytics output
        print(f"\nMV sense {resource} analytics for camera {sn}")
        print(json.dumps(analytics, indent=2))
Exemplo n.º 5
0
def main():
    """
    Execution begins here.
    """

    # Find the DevNet network ID within the DevNet organization.
    # These are default arguments when left unspecified
    devnet_network = find_network()

    # Get a list of SSIDs within the DevNet network
    ssids = req(f"networks/{devnet_network}/ssids").json()

    # Debugging line; pretty-print JSON to see structure (list of SSIDs)
    # import json; print(json.dumps(ssids, indent=2))

    # Iterate over the list of SSIDs found, printing their number,
    # enable state, and descriptive name.
    print(f"SSIDs found: {len(ssids)}")
    for ssid in ssids:
        print(f"Num: {ssid['number']:<3} Enabled: {ssid['enabled']:<2}", end="")
        print(f" Name: {ssid['name']}")
Exemplo n.º 6
0
def main(org_name, net_name):
    """
    Execution begins here.
    """

    # First, get all organizations
    orgs = req("organizations").json()

    # Print the list of organizations for troubleshooting
    print(json.dumps(orgs, indent=2))

    # See if supplied org_name is already present by looping
    # over all collected organizations
    org_id = find_id_by_name(orgs, org_name)

    # If we didn't find the organization
    if not org_id:
        # Create the organization
        body = {"name": org_name}
        new_org = req("organizations", method="post", json=body).json()
        org_id = new_org["id"]

        # The network cannot possibly exist, so also create the network
        body = {"name": net_name, "type": "wireless"}
        new_net = req(f"/organizations/{org_id}/networks",
                      method="post",
                      json=body).json()
        net_id = new_net["id"]

    # Else we did find the organization, don't recreate it
    else:
        print(f"Organization '{org_name}' exists, not recreating")

        # Second, get all networks inside that organization
        nets = req(f"organizations/{org_id}/networks").json()

        # Print the list of organizations for troubleshooting
        print(json.dumps(nets, indent=2))

        # See if supplied net_name is already present by looping
        # over all collected organization networks
        net_id = find_id_by_name(nets, net_name)

        # If we didn't find the network
        if not net_id:
            body = {"name": net_name, "type": "appliance"}
            new_net = req(f"/organizations/{org_id}/networks",
                          method="post",
                          json=body).json()
            net_id = new_net["id"]

        # Else we did find the organization, do nothing
        else:
            print(
                f"Network '{net_name}' exists in '{org_name}', not recreating")

    # Last, apply new updates to the network. We could have included these in
    # the initial POST as well. Load in the updated data from a JSON file first
    with open("update_net.json", "r") as handle:
        body = json.load(handle)

    # Issue the request and print the feedback
    # TODO consider datadiff or dictdiffer ... current vs intended?
    update_net = req(f"networks/{net_id}", method="put", json=body).json()
    print(f"Current configuration for {net_name}:")
    print(json.dumps(update_net, indent=2))
Exemplo n.º 7
0
def main(org_name):
    """
    Execution begins here.
    """

    # First, get all organizations
    orgs = req("organizations").json()

    # Print the list of organizations for troubleshooting
    # print(json.dumps(orgs, indent=2))

    # See if supplied org_name is already present by looping
    # over all collected organizations
    org_id = find_id_by_name(orgs, org_name)

    # If we didn't find the organization
    if not org_id:
        raise ValueError("Could not find organization {org_name}")

    # Second, get all networks inside that organization
    print(f"Found {org_name} with ID {org_id}")
    cur_nets = req(f"organizations/{org_id}/networks").json()

    # Print the list of networks for troubleshooting
    # print(json.dumps(cur_nets, indent=2))

    # Load in the networks to add, and iterate over them
    with open("add_networks.json", "r") as handle:
        add_nets = json.load(handle)

    for item in add_nets:

        # See if supplied network name is already present by looping
        # over all collected organization networks
        net_name = item["body"]["name"]
        net_id = find_id_by_name(cur_nets, net_name)

        # The network already exists; not an error, but gracefully exit
        if net_id:
            print(f"Network {net_name} already exists ({net_id})")
            sys.exit(0)

        # Network does not exist, so create it and capture the network ID
        new_net = req(
            f"/organizations/{org_id}/networks",
            method="post",
            json=item["body"],
        ).json()
        net_id = new_net["id"]
        print(f"Created network {net_name} with ID {net_id}")

        # Debugging statement to display new network configuration
        # print(json.dumps(new_net, indent=2))

        # Iterate over the list of devices that belong in each new network
        # and claim each device individually (no body data returned)
        for device in item["devices"]:
            req(
                f"networks/{net_id}/devices/claim",
                method="post",
                json=device["add"],
            )
            sn = device["add"]["serial"]
            print(f"Device with SN {sn} added")

            # Although unexpected, the dashboard API does *not* currently allow
            # you to specify the "name" attribute when claiming a device. This
            # must be done afterwards using a PUT request
            update = req(
                f"networks/{net_id}/devices/{sn}",
                method="put",
                json=device["update"],
            ).json()
            print(f"Device with SN {sn} named {device['update']['name']}")

            # Debugging statement to print the device details after update
            # print(json.dumps(update, indent=2))

            # Sanity check; ensure the name update actually worked
            if update["name"] != device["update"]["name"]:
                raise ValueError("Device name update failed")
Exemplo n.º 8
0
def main(net_name):
    """
    Execution begins here.
    """

    # Find the network ID for our reserved instance
    net_id = get_devnet_network_id(net_name)

    # Load in the webhooks to add from the JSON file
    with open("add_webhooks.json", "r") as handle:
        webhooks = json.load(handle)

    # For each webhook to add
    for webhook in webhooks:

        # Add each webhook server individually
        print(f"adding webhook '{webhook['name']}'")
        if not webhook["url"].lower().startswith("https"):
            print(" url is not 'https', skipping")
            continue
        add_http = req(f"networks/{net_id}/httpServers",
                       method="post",
                       json=webhook).json()

        # Print JSON structure of response for troubleshooting
        # print(json.dumps(add_http, indent=2))

        # Send a test webhook to each server based on URL
        # after waiting a few seconds to reduce race condition likelihood
        print(f"testing webhook '{webhook['name']}'")
        test_http = req(
            f"networks/{net_id}/httpServers/webhookTests",
            method="post",
            json={
                "url": webhook["url"]
            },
        ).json()

        # Ensure the webhooks are enqueued (ie, started successfully)
        if test_http["status"] != "enqueued":
            raise ValueError("webhook creation failed: {test_http['status']}")

        # Wait until the state changes from "enqueued"
        while test_http["status"] == "enqueued":

            # Print JSON structure of response for troubleshooting
            # print(json.dumps(test_http, indent=2))

            # Rewrite "test_http" to update the status every few seconds
            time.sleep(2)
            test_http = req(
                f"networks/{net_id}/httpServers/webhookTests/{test_http['id']}",
            ).json()

        # The final status should be "delivered"; if not, raise error
        # For additional confirmation, check the webhook receivers too
        if test_http["status"] != "delivered":
            raise ValueError("webhook delivery failed: {test_http['status']}")

    # Collect the current webhooks and print them as confirmation
    net_http = req(f"networks/{net_id}/httpServers").json()
    print(f"Current webhook receivers for {net_name}:")
    print(json.dumps(net_http, indent=2))