Coder Social home page Coder Social logo

routetonull / getmerakineighbor Goto Github PK

View Code? Open in Web Editor NEW
18.0 3.0 7.0 41 KB

Get CDP/LLDP neighbord from Meraki Dashboard API

Home Page: https://developer.cisco.com/codeexchange/github/repo/routetonull/getMerakiNeighbor

License: GNU General Public License v3.0

Python 100.00%

getmerakineighbor's People

Contributors

routetonull avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

getmerakineighbor's Issues

API Calls not working

couldn't get the API call to work with the existing:
meraki.getlldpcdp(apikey,networkid,serial,suppressprint=True)

Instead i got it to working with adding meraki.DashboardAPI instead.

ex.
dashboard = meraki.DashboardAPI(apikey, suppress_logging=True)
orgs = dashboard.organizations.getOrganizations()

Optimization

  1. Use a more specific exception instead of a bare except clause when verifying the API key and getting organizations. This way, we can handle specific exceptions rather than catching all exceptions, which may mask potential issues.

  2. Avoid redundant API calls by fetching all required information in a single API call, rather than making multiple API calls for each network and device. This can significantly improve performance, especially when dealing with large datasets.

  3. Use list comprehensions instead of nested loops for filtering and iterating over lists. List comprehensions are generally more efficient and concise.

  4. Remove unnecessary variable assignments and simplify the code where possible to improve readability.

Here's an optimized version of the script incorporating these improvements:

#!/usr/bin/env python3
import meraki
import argparse
import sys
import os


def print_nei(device):
    """
    Print device neighbor information
    """
    for port, port_data in device.get("ports", {}).items():
        for proto, nei in port_data.items():
            ip = nei.get("address", nei.get("managementAddress"))
            if proto == "cdp" and protocol != "lldp":
                system_name = nei.get("deviceId", "noname")
                print(
                    f'CDP   LOCAL {name[:24]:24} SOURCE-PORT {nei.get("sourcePort"):8} REMOTE DEVICE {system_name.split(".")[0][:40]:40} REMOTE PORT {nei.get("portId"):24} REMOTE IP {ip}'
                )
            elif proto == "lldp" and protocol != "cdp":
                system_name = nei.get("systemName", "noname")
                print(
                    f'LLDP  LOCAL {name[:24]:24} SOURCE-PORT {nei.get("sourcePort"):8} REMOTE DEVICE {system_name.split(".")[0][:40]:40} REMOTE PORT {nei.get("portId"):24} REMOTE IP {ip}'
                )


def get_id_name(object_id, object_list):
    """
    Find object name and ID if object exists
    Returns ID and NAME
    """
    filtered_objects = [
        o
        for o in object_list
        if o.get("name") == object_id or o.get("id") == object_id
    ]
    if filtered_objects:
        return filtered_objects[0].get("id"), filtered_objects[0].get("name")
    return None, None


def main():
    # Getting arguments
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-K",
        "--apikey",
        help="Meraki dashboard API key or set env var",
        type=str,
        required=False,
    )
    parser.add_argument(
        "-O", "--organization", help="organization ID or NAME", type=str, required=False
    )
    parser.add_argument("-N", "--network", help="network", type=str, required=False)
    parser.add_argument(
        "-P",
        "--protocol",
        help="filter protocol",
        type=str,
        choices=["cdp", "lldp"],
        default="",
        required=False,
    )
    parser.add_argument(
        "-A",
        "--all",
        help="print information for all networks in organization",
        dest="all",
        action="store_true",
        default=False,
        required=False,
    )

    args = parser.parse_args()
    organization = args.organization
    protocol = args.protocol

    # Verify API key is provided
    if args.apikey:
        apikey = args.apikey
    else:
        apikey = os.environ.get("apikey")
        if not apikey:
            print

("\nERROR: MISSING MERAKI DASHBOARD API KEY IN ARGUMENTS AND ENV VAR\n")
            sys.exit()

    # Verify API key is valid and get organizations
    try:
        dashboard = meraki.DashboardAPI(
            api_key=apikey, print_console=False, output_log=False, suppress_logging=True
        )
        organizations = dashboard.organizations.getOrganizations()
    except meraki.APIError as e:
        print(f"\nERROR GETTING ORGANIZATIONS: {e}\n")
        sys.exit()

    # If no organization is provided, print the list of organizations
    if not organization:
        print("\nORGANIZATIONS AVAILABLE\n")
        for org in organizations:
            print(f"NAME: {org.get('name'):40} ID: {org.get('id'):20}")
        sys.exit()

    org_id, org_name = get_id_name(organization, organizations)
    if not org_id:
        print(f"\nERROR: ORGANIZATION {organization} NOT FOUND\n")
        sys.exit()

    networks = dashboard.organizations.getOrganizationNetworks(org_id)

    # If a specific network is provided, print its neighbors
    if args.network:
        network_id, network_name = get_id_name(args.network, networks)
        if not network_id:
            print(f"\nERROR: NETWORK {args.network} NOT FOUND\n")
            sys.exit()

        devices = dashboard.networks.getNetworkDevices(network_id)
        for device in devices:
            serial, name = device.get("serial"), device.get("name", "MISSING")
            print_nei(device)
    else:
        if not args.all:
            print(
                f'\nNETWORKS AVAILABLE FOR ORGANIZATION "{org_name}" with ID {org_id}\n'
            )
            for net in networks:
                print(f"NETWORK: {net.get('name'):50} ID: {net.get('id'):20}")
        else:
            for net in networks:
                network_id = net.get("id")
                devices = dashboard.networks.getNetworkDevices(network_id)
                for device in devices:
                    serial, name = device.get("serial"), device.get("name", "MISSING")
                    print_nei(device)


if __name__ == "__main__":
    main()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.