コード例 #1
0
ファイル: client.py プロジェクト: sQu4rks/DNAC-Python-Wrapper
    def get_client_detail(self):
        """
        Get method get_client_detail makes a call to Cisco DNAC, retrieves the Client's state information,
        stores it in the client_detail attribute, and also returns the results for further processing.

        Parameters:
            None

        Return Values:
            dict: the Client's detailed state

        Usage:
            d = Dnac()
            host = Client(d, 'myPC', mac='a1:b2:c3:d4:e5:f6')
            pprint.PrettyPrint(d.api['myPC'].get_client_detail)
        """
        if self.__mac in ILLEGAL_MAC_ADDRS:
            raise DnacApiError(
                MODULE, 'get_client_detail', ILLEGAL_MAC, '',
                '', self.__mac, '', ''
            )
        time = TimeStamp()
        query = '?timestamp=%s&macAddress=%s' % (time, self.__mac)
        url = self.dnac.url + self.resource + query
        detail, status = self.crud.get(url,
                                       headers=self.dnac.hdrs,
                                       verify=self.verify,
                                       timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_client_detail', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(detail)
            )
        self.__client_detail = detail
        return self.__client_detail
コード例 #2
0
 def get_devices_by_name_with_regex(self, regex):
     """
     The get_devices_by_name_with_regex searches through Cisco DNA Center's inventory for all devices whose hostname
     matches the regular expression it is given.
     :param regex: A regular expression to find a device or set of network devices.
         type: str
         default: none
         required: yes
     :return: list of dict
     """
     host_filter = '?hostname=' + regex
     url = self.dnac.url + self.resource + host_filter
     devices, status = self.crud.get(url,
                                     headers=self.dnac.hdrs,
                                     verify=self.verify,
                                     timeout=self.timeout)
     if status != OK:
         raise DnacApiError(MODULE, 'get_devices_by_name_with_regex(',
                            REQUEST_NOT_OK, url, OK, status,
                            ERROR_MSGS[status], str(devices))
     if not devices['response']:  # device list is empty
         raise DnacApiError(MODULE, 'get_devices_by_name_with_regex(',
                            NO_DEVICES, url, '', str(devices['response']),
                            '', CHECK_REGEX)
     self.__devices = devices['response']
     return self.__devices
コード例 #3
0
    def commit_template(self, comments='', timeout=5):
        """
        The commit_template updates the parent template to its next version.  Once completed, the actual template
        can be deployed in Cisco DNA Center.
        :param comments: Comments for the commit action
            type: str
            required: no
            default: ''
        :return: Template object
        """
        body = {'templateId': self.template_id, 'comments': comments}
        url = '%s%s%s' % (self.dnac.url, self.resource,
                          TEMPLATE_VERSION_PATH[self.dnac.version])
        results, status = self.crud.post(url,
                                         headers=self.dnac.hdrs,
                                         body=json.dumps(body),
                                         verify=self.verify,
                                         timeout=timeout)
        if status != ACCEPTED:
            raise DnacApiError(MODULE, 'version_template',
                               REQUEST_NOT_ACCEPTED, url, ACCEPTED, status,
                               ERROR_MSGS[status], '')

        # check the tasks' results
        task = Task(self.dnac, results['response']['taskId'])
        task.get_task_results()
        if task.is_error:
            raise DnacApiError(MODULE, 'version_template',
                               TEMPLATE_VERSION_FAILED, '', '', '', '',
                               task.failure_reason)

        # version succeeded - reload the template and its versions
        return self.load_template(self.name)
コード例 #4
0
 def get_devices_by_ip_with_regex(self, regex):
     """
     The get_devices_by_ip_with_regex searches through Cisco DNA Center's inventory for all devices whose
     management IP address matches the regular expression passed.
     :param regex: A regular expression of the IP addresses to search.
         type: str
         default: none
         required: yes
     :return: list of dict
     """
     url = self.dnac.url + self.resource + \
           ('?managementIpAddress=%s' % regex)
     devices, status = self.crud.get(url,
                                     headers=self.dnac.hdrs,
                                     verify=self.verify,
                                     timeout=self.timeout)
     if status != OK:
         raise DnacApiError(MODULE, 'get_devices_by_ip_with_regex',
                            REQUEST_NOT_OK, url, OK, status,
                            ERROR_MSGS[status], str(devices))
     if not devices['response']:  # device list is empty
         raise DnacApiError(MODULE, 'get_devices_by_ip_with_regex',
                            NO_DEVICES, url, '', str(devices['response']),
                            '', CHECK_REGEX)
     self.__devices = devices['response']
     return self.__devices
コード例 #5
0
 def add_project(self, project):
     """
     Adds a project to Cisco DNA Center
     :param project: The project data represented as a dict
     :return: Project object
     """
     # add the project to Cisco DNA Center
     url = '%s%s' % (self.dnac.url, self.resource)
     self.__clean_project__(project)
     body = json.dumps(project)
     results, status = self.crud.post(url,
                                      headers=self.dnac.hdrs,
                                      body=body,
                                      verify=self.verify,
                                      timeout=self.timeout)
     if status != ACCEPTED:
         raise DnacApiError(
             MODULE, 'import_project', REQUEST_NOT_ACCEPTED, url, ACCEPTED, status, ERROR_MSGS[status], ''
         )
     # check the tasks' results
     task = Task(self.dnac, results['response']['taskId'])
     task.get_task_results()
     if task.is_error:
         raise DnacApiError(MODULE, 'import_project', PROJECT_IMPORT_FAILED, '', '', '', '', task.failure_reason)
     # import succeeded; create a new Project object, add it to Dnac and return it
     return Project(self.dnac, project['name'])
コード例 #6
0
 def get_all_sites(self):
     """
     Places an API call to the hierarchy's Cisco DNA Center cluster for all sites listed in its design hierarchy.
     :return: dict
     """
     self.__all_sites = []
     self.get_site_count()
     (rounds, remainder) = divmod(self.__site_count, SITE_REQUEST_LIMIT)
     if remainder > 0:
         rounds += 1
     if self.__site_count <= NO_SITES:
         raise DnacApiError(MODULE, 'get_all_sites', NO_SITES_ERROR, '', '',
                            '', '', '')
     i = 0
     offset = 1
     filter = '?offset=%i&limit=%i' % (offset, SITE_REQUEST_LIMIT)
     url = '%s%s%s' % (self.dnac.url, self.resource, filter)
     while i < rounds:
         # get the next batch of sites
         response, status = self.crud.get(url,
                                          headers=self.dnac.hdrs,
                                          verify=self.verify,
                                          timeout=self.timeout)
         if status != OK:
             raise DnacApiError(MODULE, 'get_all_sites', REQUEST_NOT_OK,
                                url, OK, status, ERROR_MSGS[status], '')
         self.__all_sites = self.__all_sites + response['response']
         offset += SITE_REQUEST_LIMIT
         i += 1
     return self.__all_sites
コード例 #7
0
 def get_device_by_name(self, name):
     """
     get_device_by_name finds a device in Cisco DNAC using its hostname.
     :param name: The device's hostname.
         type : str
         default: none
         required: yes
     :return: list with a single dict
     """
     host_filter = '?hostname=' + name
     url = self.dnac.url + self.resource + host_filter
     devices, status = self.crud.get(url,
                                     headers=self.dnac.hdrs,
                                     verify=self.verify,
                                     timeout=self.timeout)
     if status != OK:
         raise DnacApiError(MODULE, 'get_device_by_name', REQUEST_NOT_OK,
                            url, OK, status, ERROR_MSGS[status],
                            str(devices))
     if not devices['response']:  # device list is empty
         raise DnacApiError(MODULE,
                            'get_device_by_name', NO_DEVICES, url, '',
                            str(devices['response']), '', CHECK_HOSTNAME)
     self.__devices = devices['response'][0]
     return self.__devices
コード例 #8
0
 def deploy(self):
     """
     The deploy method asynchronously applies a template to a device. The Template's target information and
     versioned template data must be set prior to issuing this command.  The function creates a Deployment object,
     saves it, and then instructs it to perform a progress check on itself and then returns whatever Cisco DNA
     Center responds with.  Developers can then use the deployment instance to further monitor the job's success
     or failure.
     :return: str
     """
     url = self.dnac.url + self.resource + '/deploy'
     if not self.__target_id:  # target_id is not set
         raise DnacApiError(MODULE, 'deploy', EMPTY_TEMPLATE, url, '',
                            self.__target_id, '', NO_TEMPLATE_ID)
     if self.__target_type not in VALID_TARGET_TYPES:
         raise DnacApiError(
             MODULE, 'deploy', ILLEGAL_TARGET_TYPE, url,
             str(VALID_TARGET_TYPES), self.__target_type, '',
             '%s is not one of %s' %
             (self.__target_type, str(VALID_TARGET_TYPES)))
     body = self.__make_body__()
     results, status = self.crud.post(url,
                                      headers=self.dnac.hdrs,
                                      body=body,
                                      verify=self.verify,
                                      timeout=self.timeout)
     if status != ACCEPTED:
         raise DnacApiError(MODULE, 'check_deployment',
                            REQUEST_NOT_ACCEPTED, url, ACCEPTED, status,
                            ERROR_MSGS[status], str(results))
     # DNAC 1.2.8 references a deploymentId in a string
     if self.dnac.version == '1.2.8':
         did = results['response']['deploymentId']
         elts = did.split()
         deploy_id = elts[len(elts) - 1]
     # DNAC 1.2.10 uses a task that references a deploymentId in a string
     elif self.dnac.version in POST_1_2_8:
         taskUrl = '%s%s' % (self.dnac.url, results['response']['url'])
         task, status = self.crud.get(taskUrl,
                                      headers=self.dnac.hdrs,
                                      verify=self.verify,
                                      timeout=self.timeout)
         progress = task['response']['progress']
         progress_elts = progress.split(': ')
         if progress_elts[3].find(
                 TEMPLATE_ALREADY_DEPLOYED) != SUBSTR_NOT_FOUND:
             raise DnacApiError(MODULE, 'deploy_sync', ALREADY_DEPLOYED, '',
                                '', str(body), status,
                                ALREADY_DEPLOYED_RESOLUTION)
         deploy_id = progress_elts[len(progress_elts) - 1]
     else:
         raise DnacApiError(MODULE, 'deploy', UNSUPPORTED_DNAC_VERSION, '',
                            '', self.dnac.version, '', '')
     self.__deployment = Deployment(self.dnac, deploy_id)
     return self.__deployment.check_deployment()
コード例 #9
0
 def load_sites(self):
     """
     Instructs the SiteHierarchy object to load all sites from the Cisco DNA Center's site design hierarchy.  This
     method can be used to load a new hierarchy object or to refresh one that has sites which have been added or
     deleted.
     :return: dict
     """
     self.get_all_sites()
     # find the site hierarchy's root: siteNameHierarchy = "Global"
     global_site_node = None
     for site in self.__all_sites:
         if site['siteNameHierarchy'] != GLOBAL_SITE:
             continue
         else:  # found the root
             global_site = Site(self.dnac, GLOBAL_SITE)
             global_site_node = SiteNode(global_site)
             self.add_site_node(global_site_node)
             break
     if global_site_node is None:
         raise DnacApiError(MODULE, 'load_sites', NO_GLOBAL_SITE_ERROR, '',
                            '', str(global_site_node), '', '')
     # starting from the global site, load all children recursively
     #
     #  need a throttle here; this is where the majority of the site calls are being made
     #  perhaps the throttle should be part of a SiteHierarchy instance?
     #
     self.__load_children__(global_site_node)
     return self.__site_nodes
コード例 #10
0
    def get_device_by_id(self, id):
        """
        get_device_by_id finds a device in Cisco DNAC using its UUID.

        Parameters:
            id : str
                default: none
                required: yes

        Return Values:
            list: A list with a single dictionary for the UUID requested.

        Usage:
            d = Dnac()
            nd = NetworkDevice(d, 'network-device')
            d.api[nd.name] = nd
            uuid = '84e4b133-2668-4705-8163-5694c84e78fb'
            device = d.api['network-device'].get_device_by_id(uuid)
            pprint.PrettyPrint(device)
        """

        url = self.dnac.url + self.resource + ('/%s' % id)
        devices, status = self.crud.get(url,
                                        headers=self.dnac.hdrs,
                                        verify=self.verify,
                                        timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_device_by_id', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(devices)
                              )
        self.__devices = devices['response']
        return self.__devices
コード例 #11
0
    def get_all_templates(self):
        """
        Class method getAllTemplates queries the Cisco DNA Center cluster
        for a listing of every template it has.  The listing includes
        the base templates and all of its versions.

        Parameters:
            none

        Return Values:
            list: A listing of all available templates.

        Usage:
            d = Dnac()
            template = Template(d, 'Set VLAN')
            print str(d.api['Set Vlan'].getAllTemplates)
        """
        url = self.dnac.url + self.resource
        templates, status = self.crud.get(url,
                                          headers=self.dnac.hdrs,
                                          verify=self.verify,
                                          timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_all_templates', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(templates)
            )
        return templates
コード例 #12
0
    def check_deployment(self):
        """
        Deployment's check_deployment method makes an API call to Cisco
        DNA Center and collects the deploy job's current status and
        and results it returns.  It stores the data received in the
        object's __results and the job's status in __status.  It returns
        __status to the calling function.

        Parameters:
            none

        Return Values:
            str: The job's run status.

        Usage:
            d = Dnac()
            job = Deployment(d, id=<uuid>)
            print job.check_deployment()
        """
        # prepare the API call
        url = self.dnac.url + self.url
        # make the call
        results, status = self.crud.get(url,
                                        headers=self.dnac.hdrs,
                                        verify=self.verify,
                                        timeout=self.timeout)
        # return the results
        if status != ACCEPTED:
            raise DnacApiError(MODULE, 'check_deployment',
                               REQUEST_NOT_ACCEPTED, url, ACCEPTED, status,
                               ERROR_MSGS[status], str(results))
        self.__results = results
        self.__status = self.__results['status']
        return self.__status
コード例 #13
0
ファイル: site.py プロジェクト: sQu4rks/DNAC-Python-Wrapper
    def get_site_health_by_name(self, site_name):
        """
        The get_site_health_by_name returns the site health information for the named site.

        Parameters:
            site_name: The target site's name
                type: str
                default: none
                required: yes

        Return Values:
            dict: The site's health details.

        Usage:
            d = Dnac()
            all_sites = Site(d, 'ACME_sites')
            target_site = 'AZ Branch'
            pprint.PrettyPrint(d.api['ACME_sites'].get_site_health_by_name(target_site))
        """
        target_site_health = NO_SITE_HEALTH
        all_sites_health = self.get_all_sites_health()
        for site_health in all_sites_health:
            if site_health['siteName'] == site_name:
                target_site_health = site_health
                break  # found the target site
            else:
                continue  # keep searching
        if target_site_health == NO_SITE_HEALTH:  # site not found
            raise DnacApiError(MODULE, 'get_all_sites_health', SITE_NOT_FOUND,
                               '', site_name, '', '',
                               SITE_NOT_FOUND_RESOLUTION)
        self.__site_health = target_site_health
        return self.__site_health
コード例 #14
0
    def version(self, version):
        """
        The version set method changes the desired version of the template
        to be deployed.  This method also updates the versioned template,
        its UUID and its parameters in this class' respective attributes.
        See class method get_versioned_template_by_name for details.  If the
        requested version does not exist, an exception is thrown.

        Parameters:
            version: The new template version.
                type: int
                default: none
                required: yes

        Return Values:
            none

        Usage:
            d = Dnac()
            template = Template(d, 'Set VLAN')
            template.version = 5
        """
        self.__version = version
        # reload versioned template info using get_versioned_template_by_name
        self.get_versioned_template_by_name(self.name, self.__version)
        # if the version requested does not exist, raise an exception
        if not bool(self.__versioned_template):  # template is empty
            # get_versioned_template_by_name should catch this condition, but
            # just in case, here's another integrity check
            raise DnacApiError(
                MODULE, 'version setter', UNKNOWN_VERSION, '',
                '', self.__versioned_template, '',
                '%s version %i' % (self.name, version)
            )
コード例 #15
0
    def run(self):
        """
        Method run instructs Cisco DNAC to execute the command set stored in
        the CommandRunner object.  It does not wait for the task to
        complete on Cisco DNA Center.  It does, however, create a new Task
        object, saves it in the __task attribute, checks the task, and
        then returns the task's status.  See the task.py module for
        valid task states.  When using this function, the programmer
        must handle task monitoring.

        Parameters:
            none

        Return Values:
            str: The current state of the command's progress.

        Usage:
            d = Dnac()
            cmd = CommandRunner(d, 'aName')
            cmdState = cmd.run()
        """
        url = self.dnac.url + self.resource
        results, status = self.crud.post(url,
                                         headers=self.dnac.hdrs,
                                         body=self.__cmds,
                                         verify=self.verify,
                                         timeout=self.timeout)
        if status != ACCEPTED:
            raise DnacApiError(MODULE, 'run', REQUEST_NOT_ACCEPTED, url,
                               ACCEPTED, status, ERROR_MSGS[status],
                               str(results))
        task_id = results['response']['taskId']
        self.__task = Task(self.dnac, task_id)
        return self.__task.check_task()
コード例 #16
0
ファイル: site.py プロジェクト: sQu4rks/DNAC-Python-Wrapper
    def get_all_sites_health(self):
        """
        Site class method get_all_sites_health retrieves the current health details for all sites in
        Cisco DNA Center.

        Parameters:
            None

        Return Values:
            dict: The health details for all sites.

        Usage:
            d = Dnac()
            all_sites = Site(d, 'ACME_sites')
            pprint.PrettyPrint(d.api['ACME_sites'].get_all_sites_health())
        """
        time = TimeStamp()
        query = '?timestamp=%s' % time
        url = self.dnac.url + self.resource + query
        health, status = self.crud.get(url,
                                       headers=self.dnac.hdrs,
                                       verify=self.verify,
                                       timeout=self.timeout)
        if status != OK:
            raise DnacApiError(MODULE, 'get_all_sites_health', REQUEST_NOT_OK,
                               url, OK, status, ERROR_MSGS[status],
                               str(health))
        self.__site_health = health['response']
        return self.__site_health
コード例 #17
0
    def get_all_devices(self):
        """
        The get_all_devices method returns every network device managed
        by Cisco DNA Center.

        Parameters:
            none

        Return Values:
            list: A list of dictionaries.  Each dictionary contains the
                  attributes of a single device managed by Cisco DNAC.

        Usage:
            d = Dnac()
            nd = NetworkDevice(d, 'network-device')
            d.api[nd.name] = nd
            devices = d.api['network-device'].get_all_devices()
            for device in devices:
                pprint.PrettyPrint(device['hostname'])
        """
        url = self.dnac.url + self.resource
        devices, status = self.crud.get(url,
                                        headers=self.dnac.hdrs,
                                        verify=self.verify,
                                        timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_all_devices', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(devices)
                              )
        self.__devices = devices['response']
        return self.__devices
コード例 #18
0
    def get_results(self):
        """
        get_results makes an API call to Cisco DNA Center and retrieves the
        task results contained in the file identified by this object's
        __file_id, i.e. the file's UUID.

        Parameters:
            none

        Return Values:
            list: The file's or task result's data.

        Usage:
            d = Dnac()
            task = Task(d, 'aTask')
            task.checkTask()
            # task.file below is a File object
            results = task.file.get_results()
        """
        url = self.dnac.url + self.resource + ('/%s' % self.__id)
        results, status = self.crud.get(url,
                                        headers=self.dnac.hdrs,
                                        verify=self.verify,
                                        timeout=self.timeout)
        if status != OK:
            raise DnacApiError(MODULE, 'get_results', REQUEST_NOT_OK, url, OK,
                               status, ERROR_MSGS[status], str(results))
        self.__results = results
        return self.__results
コード例 #19
0
    def get_template_by_id(self, id):
        """
        get_template_by_id pulls the template information for the one
        specified by the UUID passed to the function.  Either base or
        versioned templates may be queried.

        Parameters:
            id: The UUID of a template.
                type: str
                default: none
                required: yes

        Return Values:
            dict: The template's data.

        Usage:
            d = Dnac()
            template = Template(d, 'Set VLAN')
            print str(d.api['Set Vlan'].get_template_by_id('<template_uuid>')
        """
        url = self.dnac.url + self.resource + '/' + id
        template, status = self.crud.get(url,
                                         headers=self.dnac.hdrs,
                                         verify=self.verify,
                                         timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_template_by_id', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(template)
            )
        return template
コード例 #20
0
 def get_device_detail_by_mac(self, mac):
     """
     get_device_detail_by_mac searches for a devices using its MAC address and returns a detailed listing of its
     current configuration state and health.
     :param mac: The network device's MAC address.
         type: str
         default: none
         required: yes
     :return: dict
     """
     if not self.__detail_resource:
         raise DnacError('get_device_detail_by_mac: %s: %s' %
                         (UNSUPPORTED_DNAC_VERSION, self.dnac.version))
     time = TimeStamp()
     query = '?timestamp=%s&searchBy=%s&identifier=%s' % \
             (time, mac, DEVICE_DETAIL_IDENTIFIERS['mac'])
     url = self.dnac.url + self.__detail_resource + query
     detail, status = self.crud.get(url,
                                    headers=self.dnac.hdrs,
                                    verify=self.verify,
                                    timeout=self.timeout)
     if status != OK:
         raise DnacApiError(MODULE, 'get_device_detail_by_mac',
                            REQUEST_NOT_OK, url, OK, status,
                            ERROR_MSGS[status], str(detail))
     self.__device_detail = detail['response']
     return self.__device_detail
コード例 #21
0
 def delete(self):
     """
     Removes the Version object from Cisco DNA Center as well as from the program's Dnac object.
     :return: None
     """
     url = self.dnac.url + self.resource
     results, status = self.crud.delete(url, headers=self.dnac.hdrs)
     if status != OK:
         raise DnacApiError(MODULE, 'delete', REQUEST_NOT_OK, url, OK, status, ERROR_MSGS[status], '')
     task = Task(self.dnac, results['response']['taskId'])
     task.get_task_results()
     if task.is_error:
         raise DnacApiError(MODULE, 'delete', task.progress, '', '', '', task.failure_reason, '')
     else:
         # remove self from Dnac.api{}
         del self.dnac.api[self.name]
コード例 #22
0
    def get_vlans_by_device_ip(self, ip):
        """
        get_vlans_by_device_ip obtains the list of VLANs configured on the
        device given its IP address.

        Parameters:
            ip : str
                default: none
                required: yes

        Return Values:
            list: The list of VLANs on the network device.

        Usage:
            d = Dnac()
            nd = NetworkDevice(d, 'network-device')
            ip = '10.255.1.10'
            vlans = d.api['network-device'].get_vlans_by_device_ip(ip)
            pprint.PrettyPrint(vlans)
        """
        device = self.get_device_by_ip(ip)
        url = self.dnac.url + self.resource + \
            ('/%s/l2vlan' % device['id'])
        vlans, status = self.crud.get(url,
                                      headers=self.dnac.hdrs,
                                      verify=self.verify,
                                      timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_vlans_by_device_ip', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(vlans)
                              )
        self.__vlans = vlans['response']
        return self.__vlans
コード例 #23
0
    def get_vlans_by_device_id(self, id):
        """
        get_vlans_by_device_id obtains the list of VLANs configured on the
        device given by its UUID.

        Parameters:
            id : str
                default: none
                required: yes

        Return Values:
            list: The list of VLANs on the network device.

        Usage:
            d = Dnac()
            nd = NetworkDevice(d, 'network-device')
            id = 'a0116157-3a02-4b8d-ad89-45f45ecad5da'
            vlans = d.api['network-device'].get_vlans_by_device_id(id)
            print str(vlans)
        """
        url = self.dnac.url + self.resource + ('/%s/l2vlan' % id)
        vlans, status = self.crud.get(url,
                                      headers=self.dnac.hdrs,
                                      verify=self.verify,
                                      timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_vlans_by_device_id', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(vlans)
                              )
        self.__vlans = vlans['response']
        return self.__vlans
コード例 #24
0
 def add_new_template(self, template, project, timeout=5):
     """
     Creates a new template in Cisco DNA Center and assigns it to the project provided.
     :param template: The template information constructed from a json formatted string
         type: dict
         required: yes
         default: None
     :param project: A reference to the project to which the template should be assigned
         type: Project object
         required: yes
         default: None
     :return: Template object
     """
     # ensure the template is correctly formatted
     self.__is_versioned_template__(template)
     # prepare the template for import
     template = self.__prepare_template__(template)
     # add the template into DNA Center
     url = '%s%s/%s/template' % (self.dnac.url,
                                 PROJECT_RESOURCE_PATH[self.dnac.version],
                                 project.project_id)
     body = json.dumps(template)
     results, status = self.crud.post(url,
                                      headers=self.dnac.hdrs,
                                      body=body,
                                      verify=self.verify,
                                      timeout=timeout)
     if status != ACCEPTED:
         if status == _500_:
             raise DnacApiError(MODULE, 'add_new_template',
                                REQUEST_NOT_ACCEPTED, url, ACCEPTED, status,
                                ERROR_MSGS[status], TEMPLATE_ALREADY_EXISTS)
         else:
             raise DnacApiError(MODULE, 'add_new_template',
                                REQUEST_NOT_ACCEPTED, url, ACCEPTED, status,
                                ERROR_MSGS[status], '')
     # check the tasks' results
     task = Task(self.dnac, results['response']['taskId'])
     task.get_task_results()
     if task.is_error:
         raise DnacApiError(MODULE, 'add_new_template',
                            TEMPLATE_IMPORT_FAILED, '', '', '', '',
                            task.failure_reason)
     # import succeeded; reload the project and return the new template
     project.load_project(project.name)
     return Template(self.dnac, template['name'])
コード例 #25
0
 def add_version(self, version, timeout=5):
     """
     Creates a new version of an existing template.
     :param version: The new version to be added to Cisco DNAC
         type: dict constructed from a json formatted file
         required: yes
         default: None
     :return: Template object
     """
     # ensure the template is correctly formatted
     self.__is_versioned_template__(version)
     # check if the template associated with the new version is already in Dnac
     if version['name'] not in self.dnac.api:
         # if not, throw an error
         raise DnacApiError(MODULE, 'add_version',
                            '%s %s' % (TEMPLATE_NOT_FOUND, version['name']),
                            '', '', '', '', CALL_ADD_NEW_TEMPLATE)
     else:
         # if so, save a pointer to it
         template = self.dnac.api[version['name']]
     # prepare the new version
     self.__prepare_version__(version, template)
     # add the new version to DNAC
     url = '%s%s' % (self.dnac.url,
                     TEMPLATE_RESOURCE_PATH[self.dnac.version])
     body = json.dumps(version)
     results, status = self.crud.put(url,
                                     headers=self.dnac.hdrs,
                                     body=body,
                                     verify=self.verify,
                                     timeout=timeout)
     if status != ACCEPTED:
         raise DnacApiError(MODULE, 'add_version', REQUEST_NOT_ACCEPTED,
                            url, ACCEPTED, status, ERROR_MSGS[status], '')
     # check the tasks' results
     task = Task(self.dnac, results['response']['taskId'])
     task.get_task_results()
     if task.is_error:
         raise DnacApiError(MODULE, 'add_version', TEMPLATE_IMPORT_FAILED,
                            '', '', '', '', task.failure_reason)
     # import succeeded; reload the template
     return template.load_template(version['name'])
コード例 #26
0
 def delete_config_file(self, file_id):
     """
     Removes the specified file, given by its UUID, from Cisco DNAC and from the Version instance.
     :param file_id: str
     :return: None
     """
     url = '%s%s/%s/%s' % (self.dnac.url, self.resource, CONFIG_FILE_SUB_RESOURCE_PATH[self.dnac.version], file_id)
     results, status = self.crud.delete(url, headers=self.dnac.hdrs)
     if status != OK:
         raise DnacApiError(MODULE, 'delete_config', REQUEST_NOT_OK, url, OK, status, ERROR_MSGS[status], '')
     task = Task(self.dnac, results['response']['taskId'])
     task.get_task_results()
     if task.is_error:
         raise DnacApiError(MODULE, 'delete_config', task.progress, '', '', '', task.failure_reason, '')
     else:
         for config_file_type, config_file in self.__config_files.items():
             if file_id == config_file.id:
                 del self.__config_files[config_file_type]
                 break
         del self.dnac.api['file_%s' % file_id]
コード例 #27
0
 def load_template(self, name):
     """
     The load_template method searches Cisco DNA Center for the template named.  If found, it loads the base
     template information and all available versions.  Use this function to prepare new Template objects or to
     refresh existing ones when they have changed.  Many methods in the Template class automatically call this
     function.  It should be rare for a user to have to call this method.
     :param name: The template's name as given in Cisco DNAC
         type: str
         required: yes
         default: None
     :return: Template object
     """
     # search all templates for the target
     templates = self.get_all_templates()
     if bool(templates):  # templates is not empty
         for template in templates:
             # find the template by name
             if template['name'] == name:
                 self.__template = template
                 break
             else:  # not found - keep looking for the template by its name
                 continue
         # make sure the template is not empty
         if self.__template == TEMPLATE_IS_EMPTY:
             raise DnacApiError(MODULE, 'load_template', EMPTY_TEMPLATE, '',
                                '', '', '', '')
     else:
         raise DnacApiError(MODULE, 'load_template', NO_TEMPLATES_FOUND, '',
                            '', '', '', '')
     # load the parent template
     self.__versions[0] = self.get_template_by_id(
         self.__template['templateId'])
     # load all committed versions
     if bool(self.__template['versionsInfo']
             ):  # at least one committed version exists
         for version in self.__template['versionsInfo']:
             self.__versions[int(
                 version['version'])] = self.get_template_by_id(
                     version['id'])
     # all done - return the template
     return self
コード例 #28
0
 def load_site(self, site_name_hierarchy):
     """
     Using the site's fully qualified hierarchy name, this method queries the Cisco DNA center cluster for the
     site's information and loads it into it's __site attribute.
     :param site_name_hierarchy: The site's fully qualifies site name, e.g. Global/EU/England/London
     :return: dict
     """
     filter = '?name=%s' % site_name_hierarchy
     url = '%s%s%s' % (self.dnac.url, self.resource, filter)
     site, status = self.crud.get(url,
                                  headers=self.dnac.hdrs,
                                  verify=self.verify,
                                  timeout=self.timeout)
     if status != OK:
         raise DnacApiError(MODULE, 'load_site', REQUEST_NOT_OK, url, OK,
                            status, ERROR_MSGS[status], site_name_hierarchy)
     if len(site['response']) != SINGLE_SITE:
         raise DnacApiError(MODULE, 'load_site', MULTIPLE_SITES_FOUND, '',
                            SINGLE_SITE, len(site['response']), '', '')
     self.__site = site['response'][0]
     return self.__site
コード例 #29
0
    def get_devices_by_ip_with_regex(self, regex):
        """
        The get_devices_by_ip_with_regex searches through Cisco DNA Center's
        inventory for all devices whose management IP address matches the
        regular expression passed.

        Parameters:
            regex: str
                default: None
                required: yes

        Return Values:
            list: The devices found according to the regular expression search.

        Usage:
            d = Dnac()
            nd = NetworkDevice(d, 'network-device')
            d.api[nd.name] =  nd
            regex = '192.168.*.*'
            devices = d.api['network-device'].get_devices_by_ip_with_regex(regex)
            pprint.PrettyPrint(devices)
        """
        url = self.dnac.url + self.resource + \
              ('?managementIpAddress=%s' % regex)
        devices, status = self.crud.get(url,
                                        headers=self.dnac.hdrs,
                                        verify=self.verify,
                                        timeout=self.timeout)
        if status != OK:
            raise DnacApiError(
                MODULE, 'get_devices_by_ip_with_regex', REQUEST_NOT_OK, url,
                OK, status, ERROR_MSGS[status], str(devices)
            )
        if not devices['response']:  # device list is empty
            raise DnacApiError(
                MODULE, 'get_devices_by_ip_with_regex', NO_DEVICES, url,
                '', str(devices['response']), '', CHECK_REGEX
            )
        self.__devices = devices['response']
        return self.__devices
コード例 #30
0
 def get_client_detail(self):
     """
     Get method get_client_detail makes a call to Cisco DNAC, retrieves the Client's state information, stores it in
     the client_detail attribute, and also returns the results for further processing.
     :return: dict
     """
     if self.__mac in ILLEGAL_MAC_ADDRS:
         raise DnacApiError(MODULE, 'get_client_detail', ILLEGAL_MAC, '',
                            '', self.__mac, '', '')
     time = TimeStamp()
     query = '?timestamp=%s&macAddress=%s' % (time, self.__mac)
     url = self.dnac.url + self.resource + query
     detail, status = self.crud.get(url,
                                    headers=self.dnac.hdrs,
                                    verify=self.verify,
                                    timeout=self.timeout)
     if status != OK:
         raise DnacApiError(MODULE, 'get_client_detail', REQUEST_NOT_OK,
                            url, OK, status, ERROR_MSGS[status],
                            str(detail))
     self.__client_detail = detail
     return self.__client_detail