Example #1
0
    def get_devices(self):
        """
        wrap get org inventory in lru cache
        """

        org_id = self.get_my_org_id()
        devices = meraki.getorginventory(self.apikey,
                                         org_id,
                                         suppressprint=True)
        return devices
def main(api_key, org_id):
    # Get the org's inventory
    inventory = meraki.getorginventory(api_key, org_id)

    # Filter for only MR devices
    aps = [
        device for device in inventory
        if device['model'][:2] in ('MR') and device['networkId'] is not None
    ]

    # Create array to save all the rogue APs accros the organization
    rogues = []
    for ap in aps:
        roguedata = meraki.badssid(api_key,
                                   ap['networkId'],
                                   10800,
                                   suppressprint=True)

    # Extract all rogue SSIDs single line
    #rogues.append([rogue['ssid'] for rogue in roguedata if 'ssid' in rogue])

    # Extract all rogue SSIDs to a file
    logger.info(f'Preparing the output file. Check your local directory.')
    timenow = '{:%Y%m%d_%H%M%S}'.format(datetime.now())
    filename = 'rogues_{0}.csv'.format(timenow)
    output_file = open(filename, mode='w', newline='\n')
    field_names = ['Rogue SSIDs', 'Channels']
    csv_writer = csv.writer(output_file,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_ALL)
    csv_writer.writerow(field_names)
    for rogue in roguedata:
        if 'ssid' in rogue:  #skip if no data
            csv_row = [
                data_value(rogue, 'ssid'),
                data_value(rogue, 'channels')
            ]
            csv_writer.writerow(csv_row)

    output_file.close()
    m = MultipartEncoder({
        'roomId': 'Y2lzY2.....',
        'text': 'Rogue APs File',
        'files': (filename, open(filename, 'rb'), 'image/png')
    })

    r = requests.post('https://api.ciscospark.com/v1/messages',
                      data=m,
                      headers={
                          'Authorization': 'Bearer ACCESS_TOKEN',
                          'Content-Type': m.content_type
                      })

    print r.text
Example #3
0
 def get_org_bssids(self, org_id):
     org_networks = meraki.getnetworklist(self.api_key,
                                          org_id,
                                          suppressprint=True)
     self.org_inventory = meraki.getorginventory(self.api_key,
                                                 org_id,
                                                 suppressprint=True)
     bssids = {}
     for network in org_networks:
         bssids[network['name']] = self.__get_bssids_for_network(network)
     return bssids
def get_serials_of_devices(api_key, org_id):
    '''
    [Get networks in org
        {
            "id": "N_24329156",
            "organizationId": 2930418,
            "name": "My organization",
            "timeZone": "America/Los_Angeles",
            "tags": " tag1 tag2 ",
            "type": "combined",
            "disableMyMerakiCom": false
        }
    ]   

    [Get devices in org
        {
            "mac": "00:11:22:33:44:55",
            "serial": "Q234-ABCD-5678",
            "networkId": "N_24329156",
            "model": "MR34",
            "claimedAt": 1518365681.0,
            "publicIp": "123.123.123.1",
            "name": "My AP"
        }
    ]
    '''

    #get network names first and map to IDs
    temp = {}  #{'N_12345':'test network'}
    #networkIds = []
    networks = meraki.getnetworklist(api_key, org_id, suppressprint=True)
    for network in networks:
        if 'name' in network:
            temp[network['id']] = network['name']
    inventory = meraki.getorginventory(api_key, org_id, suppressprint=True)
    #get all APs in org
    #create new Dict, only include networks with MRs, and add serial to data
    #devices = [device for device in inventory if device['model'][:2] in ('MR') and device['networkId'] is not None]
    networkIdDict = {
    }  #{'D-serial':['NID','mac','network name','model','device name']}
    for device in inventory:
        if device['serial'] and device['networkId']:
            #networkIdDict[device['networkId']] = [device['mac'],device['serial'],device['model'],temp[device['networkId']]]
            networkIdDict[device['serial']] = [
                device['networkId'], device['mac'], temp[device['networkId']],
                device['model'], device['name']
            ]
    return networkIdDict
Example #5
0
def main(api_key, org_id):
    # Get the org's inventory
    inventory = meraki.getorginventory(api_key, org_id, suppressprint=True)
    #    print (inventory)
    # Filter for only MR devices
    aps = [
        device for device in inventory
        if device['model'][:2] in ('MR') and device['networkId'] is not None
    ]
    print(aps)
    # Create array to save all the rogue APs accros the organization
    rogues = []
    for ap in aps:
        roguedata = meraki.getairmarshal(api_key,
                                         ap['networkId'],
                                         10800,
                                         suppressprint=True)
        # Chris Added line to print rogue data for debuging
        print(roguedata)
    # Extract all rogue SSIDs single line
    #rogues.append([rogue['ssid'] for rogue in roguedata if 'ssid' in rogue])

    # Extract all rogue SSIDs to a file
    logger.info(f'Preparing the output file. Check your local directory.')
    timenow = '{:%Y%m%d_%H%M%S}'.format(datetime.now())
    filename = 'rogues_{0}.csv'.format(timenow)
    output_file = open(filename, mode='w', newline='\n')
    field_names = ['Rogue SSIDs', 'Channels']
    #   field_names = ['Rogue SSIDs', 'Channels', 'detectedBy']
    csv_writer = csv.writer(output_file,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_ALL)
    csv_writer.writerow(field_names)
    for rogue in roguedata:
        if 'ssid' in rogue:  #skip if no data
            csv_row = [
                data_value(rogue, 'ssid'),
                data_value(rogue, 'channels')
            ]
            #           csv_row = [data_value(rogue, 'ssid'), data_value(rogue, 'channels'), data_value(rogue, 'detectedBy')]
            csv_writer.writerow(csv_row)

    output_file.close()
Example #6
0
def pod_status(d):
    ret = ""
    netinfo = meraki.getnetworkdetail(merakiapikey, d["role"], suppressprint=True)
    if netinfo:
        networkname = netinfo["name"]
        netid = d["role"]
        ret += "Network Name: " + networkname + "\nNetwork ID: " + netid + "\n"

        orgdevinv = meraki.getorginventory(merakiapikey, merakiorgnum, suppressprint=True)
        devlist = []
        for d in devdict:
            devlist.append(devdict[d])
        for d in orgdevinv:
            if d["serial"] in devlist:
                if d["networkId"] == netid:
                    ret += "<li>" + d["serial"] + " - Present In Network\n"
                else:
                    ret += "<li>" + d["serial"] + " - Missing From Network\n"

        return ret
    else:
        return "This Network Does Not Exist\n" + str(d)
Example #7
0
def main(argv):
    # Set default values for command line arguments
    api_key = org_id = arg_tag = arg_policy = arg_mode = None

    # Get command line arguments
    try:
        opts, args = getopt.getopt(argv, 'hk:o:t:p: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 == '-o':
            org_id = arg
        elif opt == '-t':
            arg_tag = arg
        elif opt == '-p':
            arg_policy = arg
        elif opt == '-m':
            arg_mode = arg

    # Check if all required parameters have been input
    if api_key == None or org_id == None or arg_tag == None or arg_policy == None:
        print_help()
        sys.exit(2)

    # Assign default mode to "simulate" unless "commit" specified
    if arg_mode != 'commit':
        arg_mode = 'simulate'

    # Get org's inventory
    inventory = meraki.getorginventory(api_key, org_id)

    # Filter for only MV devices
    cameras = [device for device in inventory if device['model'][:2] in ('MV') and device['networkId'] is not None]

    # Gather the networks (IDs) where cameras have been added
    camera_network_ids = set([camera['networkId'] for camera in cameras])
    logger.info('Found a total of {0} cameras added to {1} networks in this Dashboard organization'.format(len(cameras), len(camera_network_ids)))

    # Iterate through camera networks and find cameras with specified tag
    camera_macs = []
    for net_id in camera_network_ids:
        devices = meraki.getnetworkdevices(api_key, net_id)
        for device in devices:
            if device['model'][:2] == 'MV' and 'tags' in device and arg_tag in device['tags']:
                camera_macs.append(device['mac'])
    logger.info('Found {0} cameras with the tag "{1}"'.format(len(camera_macs), arg_tag))

    # Get list of all networks in org
    networks = meraki.getnetworklist(api_key, org_id)

    # Iterate through all networks, looking for cameras as clients, and apply group policy
    for network in networks:
        # Get the Meraki devices in this network
        devices = meraki.getnetworkdevices(api_key, network['id'])
        
        # Filter for just the first two characters of each device model
        device_models = [device['model'][:2] for device in devices]

        # Is there an MX here? If so, get its index in the list of devices
        if 'MX' in device_models:
            # We found the MX device in the network
            mx_device = devices[device_models.index('MX')]
        else:
            # No MX in this network, doesn't make sense to apply a group policy to wired clients (cameras), so move on
            continue

        # Get list of MX clients
        clients = meraki.getclients(api_key, mx_device['serial'], timestamp=2592000)

        # Filter for MAC addresses of these clients
        client_macs = [client['mac'] for client in clients]

        # Cameras in this network = intersection of clients in this network and cameras in the org
        network_cameras = set(client_macs).intersection(camera_macs)

        # Assign group policy to these cameras in the network
        if network_cameras:
            # Gather group policies of network
            gps = meraki.getgrouppolicies(api_key, network['id'])

            # Get human-readable names of all group policies
            gp_names = [gp['name'] for gp in gps]

            # Look for the group policy
            gp_camera = gps[gp_names.index(arg_policy)]

            # Assign that group policy (by ID) to the camera by MAC address
            for mac in network_cameras:
                if arg_mode == 'commit':
                    meraki.updateclientpolicy(api_key, network['id'], mac, policy='group', policyid=gp_camera['groupPolicyId'])
                    logger.info('Assigning group policy "{0}" on network "{1}" for MV camera {2}'.format(arg_policy, network['name'], mac))
                else:
                    logger.info('Simulating group policy "{0}" on network "{1}" for MV camera {2}'.format(arg_policy, network['name'], mac))
Example #8
0
# Add the new network
else:
    # Call to create a newtork
    my_network = meraki.addnetwork(my_key, my_org, my_name, 'wireless',
                                   my_tags, my_time)
    my_netid = my_network['id']
    print('Part 1: created network {0} with network ID {1}\n'.format(
        my_name, my_netid))

# 2. Return the inventory for an organization

#########################
##### START EDITING #####
# Call to return the inventory for an organization
# One line similar to above line 33's call on meraki.getnetworklist()
inventory = meraki.getorginventory()
###### END EDITING ######
#########################

# Filter out used devices already allocated to networks
unused = [device for device in inventory if device['networkId'] is None]
print('Part 2: found total of {0} unused devices in inventory\n'.format(
    len(unused)))

# 3. Claim a device into a network

# Check if network already contains a device
my_network_devices = meraki.getnetworkdevices(my_key, my_netid)

# No device in network yet
if len(my_network_devices) == 0:
Example #9
0
# Add the new network
else:
    # Call to create a newtork
    my_network = meraki.addnetwork(my_key, my_org, my_name, 'wireless',
                                   my_tags, my_time)
    my_netid = my_network['id']
    print('Part 1: created network {0} with network ID {1}\n'.format(
        my_name, my_netid))

# 2. Return the inventory for an organization

#########################
##### START EDITING #####
# Call to return the inventory for an organization
# One line similar to above line 33's call on meraki.getnetworklist()
inventory = meraki.getorginventory(my_key, my_org)
###### END EDITING ######
#########################

# Filter out used devices already allocated to networks
unused = [device for device in inventory if device['networkId'] is None]
print('Part 2: found total of {0} unused devices in inventory\n'.format(
    len(unused)))

# 3. Claim a device into a network

# Check if network already contains a device
my_network_devices = meraki.getnetworkdevices(my_key, my_netid)

# No device in network yet
if len(my_network_devices) == 0:
Example #10
0
def main(api_key, org_id):
    # Get the org's inventory
    inventory = meraki.getorginventory(api_key, org_id, suppressprint=True)
    # Filter for only MR devices
    aps = [
        device for device in inventory
        if device['model'][:2] in ('MR') and device['networkId'] is not None
    ]
    #networkList needed later on for mapping Device to Network ID
    networkList = []
    for ap in aps:
        networkList.append([ap['serial'], ap['networkId']])
    #used to concat all the dataframes (rows for CSVs)
    frames = []

    logger.info('Preparing the output file. Check your local directory.')
    timenow = '{:%Y%m%d_%H%M%S}'.format(datetime.now())
    filename = 'rogues_{0}.csv'.format(timenow)
    #####Added CSV writer so that CSV file would write while performing API iteration
    ##### Helps for when there are unexpected crashes or timeouts, we can still have some data
    temp_filename = 'temp_rogues_{0}.csv'.format(timenow)
    output_file = open(temp_filename, mode='w', newline='\n')
    field_names = [
        'SSID', 'Channels', 'Device SN', 'Network ID', 'First Seen',
        'Last Seen', 'Plugged in Time'
    ]
    csv_writer = csv.DictWriter(output_file,
                                fieldnames=field_names,
                                restval='')
    csv_writer.writeheader()
    ###### End CSV init
    n = 1000  #used to print screen every n rogue ID found
    x = 0

    for ap in aps:
        #iterate through all network IDs and store each temporarily in roguedata
        try:
            #print(str(ap))
            roguedata = meraki.getairmarshal(api_key,
                                             ap['networkId'],
                                             3600,
                                             suppressprint=True)
            #go through each rogue SSID per Network ID
            for rogue in roguedata:
                if 'ssid' in rogue:  #skip if no data

                    ssidName = data_value(rogue, 'ssid')
                    channels = data_value(rogue, 'channels')
                    deviceSN = data_value2(rogue, 'bssids', 'detectedBy',
                                           'device')
                    networkID = get_network_id(
                        networkList,
                        data_value2(rogue, 'bssids', 'detectedBy', 'device'))
                    firstSeen = data_value(rogue, 'firstSeen')
                    lastSeen = data_value(rogue, 'lastSeen')
                    wiredLast = data_value(rogue, 'wiredLastSeen')

                    #Write CSV data row by row
                    data = {
                        'SSID': ssidName,
                        'Channels': channels,
                        'Device SN': deviceSN,
                        'Network ID': networkID,
                        'First Seen': firstSeen,
                        'Last Seen': lastSeen,
                        'Plugged in Time': wiredLast
                    }
                    csv_writer.writerow(data)
                    #output to screen every n iterations of CSV lines
                    if x % n == 0:
                        logger.info(
                            "Processing Rogue SSIDs.  Count = {0}".format(
                                str(x)))
                        #print("Processing Rogue SSIDs.  Count = "+str(x))
                x += 1

        except Exception as e:
            print(e)
            logger.error("Problem with AP:   {0}".format(str(ap)))
            #print("\nProblem with AP: \n"+ str(ap))

    output_file.close()  #close out temp_rogue file
    #print("Adding Network names to CSV file")
    logger.info("Adding Network names to CSV file")
    master_df = pd.read_csv(
        temp_filename)  #reopen temp csv and import to pandas for processing
    master_df = add_network_name(
        master_df, api_key)  #get network name associated to each AP ID
    master_df = convert_dates(
        master_df)  #format DateTime to be consistent and readable
    #reorder CSV data
    master_df = master_df[[
        'Network Name', 'SSID', 'Channels', 'Device SN', 'Network ID',
        'First Seen', 'Last Seen', 'Plugged in Time'
    ]]
    master_df = master_df.reset_index(drop=True)  #drop dataframe index
    master_df = master_df.sort_values(['Network Name'
                                       ])  #sort CSV by network name
    master_df.to_csv(filename, index=False)  #write to final rogue CSV file
    #remove temp CSV file because final report was generated
    if os.path.exists(temp_filename):
        os.remove(temp_filename)
    else:
        #print("The file does not exist")
        logger.error("The temp CSV file does not exist")
Example #11
0
def main(argv):
    # Set default values for command line arguments
    api_key = org_id = arg_tag = arg_policy = arg_mode = None

    # Get command line arguments
    try:
        opts, args = getopt.getopt(argv, 'hk:o:t:p: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 == '-o':
            org_id = arg
        elif opt == '-t':
            arg_tag = arg
        elif opt == '-p':
            arg_policy = arg
        elif opt == '-m':
            arg_mode = arg

    # Check if all required parameters have been input
    if api_key == None or org_id == None or arg_tag == None or arg_policy == None:
        print_help()
        sys.exit(2)

    # Assign default mode to "simulate" unless "commit" specified
    if arg_mode != 'commit':
        arg_mode = 'simulate'

    # Get org's inventory
    inventory = meraki.getorginventory(api_key, org_id)

    # Filter for only MV devices
    cameras = [
        device for device in inventory
        if device['model'][:2] in ('MV') and device['networkId'] is not None
    ]

    # Gather the networks (IDs) where cameras have been added
    camera_network_ids = set([camera['networkId'] for camera in cameras])
    logger.info(
        'Found a total of {0} cameras added to {1} networks in this Dashboard organization'
        .format(len(cameras), len(camera_network_ids)))

    # Iterate through camera networks and find cameras with specified tag
    camera_macs = []
    for net_id in camera_network_ids:
        devices = meraki.getnetworkdevices(api_key, net_id)
        for device in devices:
            if device[
                    'model'][:
                             2] == 'MV' and 'tags' in device and arg_tag in device[
                                 'tags']:
                camera_macs.append(device['mac'])
    logger.info('Found {0} cameras with the tag "{1}"'.format(
        len(camera_macs), arg_tag))

    # Get list of all networks in org
    networks = meraki.getnetworklist(api_key, org_id)

    # Iterate through all networks, looking for cameras as clients, and apply group policy
    for network in networks:
        # Get the Meraki devices in this network
        devices = meraki.getnetworkdevices(api_key, network['id'])

        # Filter for just the first two characters of each device model
        device_models = [device['model'][:2] for device in devices]

        # Is there an MX here? If so, get its index in the list of devices
        if 'MX' in device_models:
            # We found the MX device in the network
            mx_device = devices[device_models.index('MX')]
        else:
            # No MX in this network, doesn't make sense to apply a group policy to wired clients (cameras), so move on
            continue

        # Get list of MX clients
        clients = meraki.getclients(api_key,
                                    mx_device['serial'],
                                    timestamp=2592000)

        # Filter for MAC addresses of these clients
        client_macs = [client['mac'] for client in clients]

        # Cameras in this network = intersection of clients in this network and cameras in the org
        network_cameras = set(client_macs).intersection(camera_macs)

        # Assign group policy to these cameras in the network
        if network_cameras:
            # Gather group policies of network
            gps = meraki.getgrouppolicies(api_key, network['id'])

            # Get human-readable names of all group policies
            gp_names = [gp['name'] for gp in gps]

            # Look for the group policy
            gp_camera = gps[gp_names.index(arg_policy)]

            # Assign that group policy (by ID) to the camera by MAC address
            for mac in network_cameras:
                if arg_mode == 'commit':
                    meraki.updateclientpolicy(
                        api_key,
                        network['id'],
                        mac,
                        policy='group',
                        policyid=gp_camera['groupPolicyId'])
                    logger.info(
                        'Assigning group policy "{0}" on network "{1}" for MV camera {2}'
                        .format(arg_policy, network['name'], mac))
                else:
                    logger.info(
                        'Simulating group policy "{0}" on network "{1}" for MV camera {2}'
                        .format(arg_policy, network['name'], mac))