Example #1
0
    def delete(self):
        '''
        Perform DELETE call to delete OSPF Interface

        '''

        uri = "{base_url}{class_uri}/{id}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            id=self.interface_name)

        try:
            response = self.session.s.delete(uri,
                                             verify=False,
                                             proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info("SUCCESS: Delete OSPF Interface table\
                         entry {} succeeded".format(self.interface_name))

        # Delete back reference from ospf_areas
        for ospf_interface in self.__parent_ospf_area.ospf_interfaces:
            if ospf_interface.interface_name == self.interface_name:
                self.__parent_ospf_area.ospf_interfaces.remove(ospf_interface)

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)
Example #2
0
    def delete(self):
        '''
        Perform DELETE call to delete specified Static Route table entry.

        '''

        uri = "{base_url}{class_uri}/{prefix}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            prefix=self.reference_address
        )

        try:
            response = self.session.s.delete(
                uri, verify=False, proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info(
                "SUCCESS: Delete static_route table entry {} succeeded".format(
                    self.prefix))

        # Delete back reference from VRF
        for static_route in self.__parent_vrf.static_routes:
            if static_route.prefix == self.prefix:
                self.__parent_vrf.static_routes.remove(static_route)

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)
Example #3
0
    def get_all(cls, session):
        '''
        Perform a GET call to retrieve all system VRFs and create a dictionary containing them
        :param cls: Object's class
        :param session: pyaoscx.Session object used to represent a logical
            connection to the device
        :return: Dictionary containing VRF names as keys and a Vrf objects as
            values
        '''
        logging.info("Retrieving the VRFs inside the switch")

        uri = '{base_url}{class_uri}'.format(base_url=session.base_url,
                                             class_uri=Vrf.base_uri)

        try:
            response = session.s.get(uri, verify=False, proxies=session.proxy)
        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        data = json.loads(response.text)

        vrfs_dict = {}
        # Get all URI elements in the form of a list
        uri_list = session.api_version.get_uri_from_data(data)

        for uri in uri_list:
            # Create Vrf object
            name, vrf = Vrf.from_uri(session, uri)
            # Set VRF in dictionary
            vrfs_dict[name] = vrf

        return vrfs_dict
Example #4
0
    def delete(self):
        '''
        Perform DELETE call to delete VRF Address Family table entry

        '''

        uri = "{base_url}{class_uri}/{address_family}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            address_family=self.address_family)

        try:
            response = self.session.s.delete(uri,
                                             verify=False,
                                             proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info(
                "SUCCESS: Delete VRF Address Family table entry {} succeeded\
                    ".format(self.address_family))

        # Delete back reference from VRF
        for vrf_address_family in self.__parent_vrf.address_families:
            if vrf_address_family.address_family == self.address_family:
                self.__parent_vrf.address_families.remove(vrf_address_family)

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)
Example #5
0
    def delete(self):
        '''
        Perform DELETE call to delete  OSPF Router table entry.

        '''

        uri = "{base_url}{class_uri}/{instance_tag}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            instance_tag=self.instance_tag)

        try:
            response = self.session.s.delete(uri,
                                             verify=False,
                                             proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info(
                "SUCCESS: Delete OSPF Router table entry {} succeeded".format(
                    self.instance_tag))

        # Delete back reference from VRF
        for ospf_router in self.__parent_vrf.ospf_routers:
            if ospf_router.instance_tag == self.instance_tag:
                self.__parent_vrf.ospf_routers.remove(ospf_router)

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)
Example #6
0
    def tftp_switch_config_from_remote_location(self, config_file_location,
                                                config_name, vrf):
        '''
        TFTP switch config from TFTP server.
        :param config_file_location: TFTP server address and path for uploading configuration.
        :param config_name: Config file or checkpoint to be uploaded to. When using TFTP
            only running-config or startup-config can be used.
        :param vrf: VRF to be used to contact TFTP server, required if remote_output_file_tftp_path is provided.
        :return success: Return True if response is successful or False if it was not.
        '''
        success = False
        uri = '{base_url}fullconfigs/'\
              '{cfg}?from={dest}&vrf={vrf}'.format(
                  base_url=self.session.base_url,
                  cfg=config_name,
                  dest=config_file_location,
                  vrf=vrf)

        try:
            response = self.session.s.put(
                uri, verify=False,
                proxies=self.session.proxy)

            success = True

        except Exception as e:
            raise ResponseError('PUT', e)

        if not utils._response_ok(response, "PUT"):
            raise GenericOperationError(response.text, response.status_code)

        return success
Example #7
0
    def create_checkpoint(self, source_config, destination_config):
        '''
        Perform a PUT request to create a new checkpoint or copy an
            existing checkpoint to AOS-CX switch config.

        :param source_config: Name of the source configuration
            from which checkpoint needs to be created or copied.
        :param destination_config: Name of the destination configuration
            or name of checkpoint.
        :return bool: True if success

        '''
        success = False

        uri = '{base_url}fullconfigs/{dest}?from={prefix}fullconfigs/{src}'.format(
            base_url=self.session.base_url,
            prefix=self.session.resource_prefix,
            dest=destination_config,
            src=source_config)

        try:
            response = self.session.s.put(
                uri, verify=False,
                proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('PUT', e)

        if not utils._response_ok(response, "PUT"):
            raise GenericOperationError(response.text, response.status_code)

        success = True

        # Return result
        return success
Example #8
0
    def get_full_config(self, config_name='running-config'):
        '''
        Perform a GET request to obtain the device's full config
        :param config_name: String with the local-config name wanted
            Defaults to running-config
        :return config_data: Data containing the full configuration
        '''
        uri = "{base_url}fullconfigs/{cfg}".format(
            base_url=self.session.base_url,
            cfg=config_name
        )
        try:
            response = self.session.s.get(
                uri, verify=False,
                proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        # Configurable data
        config_data = json.loads(response.text)

        return config_data
Example #9
0
    def delete(self):
        '''
        Perform DELETE call to delete VRF table entry.

        '''

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)

        uri = "{base_url}{class_uri}/{name}".format(
            base_url=self.session.base_url,
            class_uri=Vrf.base_uri,
            name=self.name)

        try:
            response = self.session.s.delete(uri,
                                             verify=False,
                                             proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info("SUCCESS: Delete VRF table entry '%s' succeeded" %
                         self.name)
Example #10
0
    def delete(self):
        '''
        Perform DELETE call to delete  BGP Neighbor table entry.

        '''

        uri = "{base_url}{class_uri}/{id}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            id=self.ip_or_ifname_or_group_name)

        try:
            response = self.session.s.delete(uri,
                                             verify=False,
                                             proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info("SUCCESS: Delete BGP table entry {} succeeded".format(
                self.ip_or_ifname_or_group_name))

        # Delete back reference from BGP_Routers
        for neighbor in self.__parent_bgp_router.bgp_neighbors:
            if neighbor.ip_or_ifname_or_group_name == \
                    self.ip_or_ifname_or_group_name:
                self.__parent_bgp_router.bgp_neighbors.remove(neighbor)

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)
Example #11
0
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing static_nexthop

        :return modified: True if Object was modified and a PUT request was made.
            False otherwise

        '''
        # Variable returned
        modified = False

        static_nexthop_data = {}

        static_nexthop_data = utils.get_attrs(self, self.config_attrs)

        # Get port uri
        if hasattr(self, 'port') and \
                self.port is not None:
            static_nexthop_data["port"] = \
                self.port.get_info_format()

        uri = "{base_url}{class_uri}/{id}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            id=self.id)

        # Compare dictionaries
        if static_nexthop_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:
            post_data = json.dumps(static_nexthop_data,
                                   sort_keys=True,
                                   indent=4)

            try:
                response = self.session.s.put(uri,
                                              verify=False,
                                              data=post_data,
                                              proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(response.text,
                                            response.status_code)

            else:
                logging.info(
                    "SUCCESS: Update static_nexthop table entry {} succeeded".
                    format(self.id))

            # Set new original attributes
            self.__original_attributes = static_nexthop_data

            # Object was modified
            modified = True
        return modified
Example #12
0
    def delete(self):
        '''
        Perform DELETE call to delete ACL Entry from parent ACL on the switch.

        '''

        uri = "{base_url}{class_uri}/{sequence_number}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            sequence_number=self.sequence_number)

        try:
            response = self.session.s.delete(uri,
                                             verify=False,
                                             proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('DELETE', e)

        if not utils._response_ok(response, "DELETE"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info(
                "SUCCESS: Delete ACL Entry table entry {} succeeded".format(
                    self.sequence_number))

        # Delete back reference from ACL
        for acl_entry in self.__parent_acl.cfg_aces:
            if acl_entry.sequence_number == self.sequence_number:
                self.__parent_acl.cfg_aces.remove(acl_entry)

        # Delete object attributes
        utils.delete_attrs(self, self.config_attrs)
Example #13
0
    def create(self):
        '''
        Perform a POST call to create a new  OSPF Router table entry
        Only returns if an exception is not raise

        :return modified: True if entry was created

        '''

        ospf_router_data = {}

        ospf_router_data = utils.get_attrs(self, self.config_attrs)
        ospf_router_data['instance_tag'] = self.instance_tag

        # Set passive_interfaces into correct form
        if hasattr(self, 'passive_interfaces') \
                and self.passive_interfaces is not None:
            formated_interfaces = {}

            # Set interfaces into correct form
            for element in self.passive_interfaces:
                # Verify object is materialized
                if not element.materialized:
                    raise VerificationError(
                        'Interface {}'.format(element.name),
                        'Object inside passive_interfaces not materialized')
                formated_element = element.get_info_format()
                formated_interfaces.update(formated_element)

            # Set values in correct form
            ospf_router_data["passive_interfaces"] = formated_interfaces

        uri = "{base_url}{class_uri}".format(base_url=self.session.base_url,
                                             class_uri=self.base_uri)
        post_data = json.dumps(ospf_router_data, sort_keys=True, indent=4)

        try:
            response = self.session.s.post(uri,
                                           verify=False,
                                           data=post_data,
                                           proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('POST', e)

        if not utils._response_ok(response, "POST"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info("SUCCESS: Adding OSPF table entry {} succeeded\
                ".format(self.instance_tag))

        # Get all object's data
        self.get()
        # Object was created
        return True
Example #14
0
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing  BGP Neighbor table entry

        :return modified: True if Object was modified and a PUT request was made.
            False otherwise

        '''
        # Variable returned
        modified = False

        bgp_neighbor_data = {}

        bgp_neighbor_data = utils.get_attrs(self, self.config_attrs)

        # Get ISL port uri
        if self.local_interface is not None:
            bgp_neighbor_data["local_interface"] = \
                self.local_interface.get_info_format()

        uri = "{base_url}{class_uri}/{id}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            id=self.ip_or_ifname_or_group_name)

        # Compare dictionaries
        if bgp_neighbor_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:
            put_data = json.dumps(bgp_neighbor_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(uri,
                                              verify=False,
                                              data=put_data,
                                              proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(response.text,
                                            response.status_code)

            else:
                logging.info(
                    "SUCCESS: Update BGP table entry {} succeeded".format(
                        self.ip_or_ifname_or_group_name))
            # Set new original attributes
            self.__original_attributes = bgp_neighbor_data
            # Object was modified
            modified = True
        return modified
Example #15
0
    def create(self):
        '''
        Perform a POST call to create a new BGP Neighbor table entry
        Only returns if an exception is not raise

        :return modified: Boolean, True if entry was created

        '''

        bgp_neighbor_data = {}

        bgp_neighbor_data = utils.get_attrs(self, self.config_attrs)
        bgp_neighbor_data['ip_or_ifname_or_group_name'] = \
            self.ip_or_ifname_or_group_name

        if hasattr(self, 'local_interface'):

            # If local interface is NOT a string
            if not isinstance(self.local_interface, str):
                if not self.local_interface.materialized:
                    raise VerificationError('Local Interface',
                                            'Object not materialized')

                # Get ISL port uri
                bgp_neighbor_data["local_interface"] = \
                    self.local_interface.get_info_format()

        uri = "{base_url}{class_uri}".format(base_url=self.session.base_url,
                                             class_uri=self.base_uri)
        post_data = json.dumps(bgp_neighbor_data, sort_keys=True, indent=4)

        try:
            response = self.session.s.post(uri,
                                           verify=False,
                                           data=post_data,
                                           proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('POST', e)

        if not utils._response_ok(response, "POST"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info("SUCCESS: Adding BGP table entry {} succeeded".format(
                self.ip_or_ifname_or_group_name))

        # Get all object's data
        self.get()

        # Object was modified, as it was created inside Device
        return True
Example #16
0
    def upload_switch_config_from_local(self,
                                        config_json=None,
                                        config_file=None,
                                        config_name=None):
        '''
        Uploads configuration from a configuration file.
        :param config_name:  String with the Config file or checkpoint to be uploaded to.
            When using TFTP only running-config or startup-config can be used.
            Default: None.
        :param config_file: String with the File name and path for locally downloading
            configuration, only JSON version of configuration will be downloaded.
            Default: None.
        :param config_json: String with the JSON file name and path for locally uploading configuration,
            only JSON version of configuration can be uploaded.
            Default: None.
        :return success: Return boolean True if response is successful or False if it was not.
        '''
        success = False

        if config_json:
            with open(config_json) as json_file:
                config_json = json.load(json_file)

        if config_file:
            with open(config_file) as json_file:
                config_json = json.load(json_file)

        config_json = json.dumps(config_json)

        # Create URI from the session base url and the configuration name
        uri = '{base_url}fullconfigs/{cfg}'.format(
            base_url=self.session.base_url,
            cfg=config_name
        )
        try:
            # Put (REST) configuration file
            response = self.session.s.put(
                url=uri,
                verify=False,
                proxies=self.session.proxy,
                data=config_json)

            success = True

        except Exception as e:
            raise ResponseError('PUT', e)

        if not utils._response_ok(response, "PUT"):
            raise GenericOperationError(
                response.text, response.status_code)

        return success
Example #17
0
    def get_facts(cls, session):
        '''
        Modify this to Perform a GET call to retrieve all VLANs and their respective data
        :param cls: Class reference.
        :param session: pyaoscx.Session object used to represent a logical
            connection to the device
        
        :return facts: Dictionary containing VLAN IDs as keys and Vlan objects as values
        
        '''
        # Log
        logging.info("Retrieving switch VLANs facts")

        # Set VLAN facts depth
        vlan_depth = session.api_version.default_facts_depth

        # Build URI
        uri = '{base_url}{class_uri}?depth={depth}'.format(
            base_url=session.base_url,
            class_uri=Vlan.base_uri,
            depth=vlan_depth
        )

        try:
            # Try to get facts data via GET method 
            response = session.s.get(
                uri, 
                verify=False, 
                proxies=session.proxy 
            )

        except Exception as e:
            raise ResponseError('GET', e)
        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(
                response.text, 
                response.status_code)
        
        # Load response text into json format
        facts = json.loads(response.text)

        # Delete internal VLANs
        internal_vlan_list = []
        for vlan in facts.keys():
            if 'type' in facts[vlan].keys():
                if facts[vlan]['type'] == 'internal':
                    internal_vlan_list.append(vlan)

        for vlan in internal_vlan_list:
            facts.pop(vlan)

        return facts
Example #18
0
    def create(self):
        '''
        Perform a POST call to create a new ACL Entry.
        Only returns if an exception is not raise

        :return modified: Boolean, True if entry was created

        '''

        acl_entry_data = {}

        acl_entry_data = utils.get_attrs(self, self.config_attrs)
        acl_entry_data['sequence_number'] = self.sequence_number

        uri = "{base_url}{class_uri}".format(base_url=self.session.base_url,
                                             class_uri=self.base_uri)

        # Try to get protocol number
        try:
            if isinstance(self.protocol, str):
                if self.protocol == 'any' or self.protocol == '':
                    acl_entry_data.pop('protocol')
                else:
                    protocol_num = self.protocol_dict[self.protocol]
                    acl_entry_data['protocol'] = protocol_num
            elif isinstance(self.protocol, int):
                acl_entry_data['protocol'] = self.protocol
        except Exception:
            pass
        post_data = json.dumps(acl_entry_data, sort_keys=True, indent=4)

        try:
            response = self.session.s.post(uri,
                                           verify=False,
                                           data=post_data,
                                           proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('POST', e)

        if not utils._response_ok(response, "POST"):
            raise GenericOperationError(response.text, response.status_code)

        else:
            logging.info("SUCCESS: Adding ACL Entry table entry {} succeeded\
                ".format(self.sequence_number))

        # Get all object's data
        self.get()

        # Object was created, means modified
        return True
Example #19
0
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing DHCP Relay table entry

        :return modified: True if Object was modified and a PUT request was made.
            False otherwise

        '''
        # Variable returned
        modified = False
        dhcp_relay_data = {}

        dhcp_relay_data = utils.get_attrs(self, self.config_attrs)

        uri = "{base_url}{class_uri}/{id1}{separator}{id2}".format(
            base_url=self.session.base_url,
            class_uri=DhcpRelay.base_uri,
            id1=self.vrf.name,
            separator=self.session.api_version.compound_index_separator,
            id2=self.port.percents_name
        )

        # Compare dictionaries
        if dhcp_relay_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:

            post_data = json.dumps(dhcp_relay_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(
                    uri, verify=False, data=post_data, proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(
                    response.text, response.status_code)

            else:
                logging.info(
                    "SUCCESS: Update DHCP Relay table entry {} succeeded")
            # Set new original attributes
            self.__original_attributes = dhcp_relay_data

            # Object was modified, returns True
            modified = True
        return modified
Example #20
0
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing Aggregate Address table entry

        :return modified: True if Object was modified and a PUT request was made.
            False otherwise

        '''
        # Variable returned
        modified = False
        agg_address_data = {}

        agg_address_data = utils.get_attrs(self, self.config_attrs)

        uri = "{base_url}{class_uri}/{id1}{separator}{id2}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            id1=self.address_family,
            separator=self.session.api_version.compound_index_separator,
            id2=self.reference_ip_prefix)
        # Compare dictionaries
        if agg_address_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:
            post_data = json.dumps(agg_address_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(uri,
                                              verify=False,
                                              data=post_data,
                                              proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(response.text,
                                            response.status_code)

            else:
                logging.info(
                    "SUCCESS: Update Aggregate Address table entry {} succeeded\
                        ".format(self.address_family))
            # Set new original attributes
            self.__original_attributes = agg_address_data

            # Object was modified
            modified = True
        return modified
Example #21
0
    def __set_to_default(self):
        '''
        Perform a PUT call to set Interface to default settings
        :return: True if object was changed
        '''

        uri_ports = "{base_url}{class_uri}/{name}".format(
            base_url=self.session.base_url,
            class_uri=Interface.base_uri_ports,
            name=self.percents_name
        )

        # get Port data related to configuration
        port_data = {}

        # Set interfaces into correct form
        if "interfaces" in port_data:
            if self.__is_special_type and self.name == 'lag':
                self.interfaces = []
                for element in self.__prev_interfaces:
                    # If element was deleted from interfaces
                    if element not in self.interfaces:
                        # Delete element reference to current LAG
                        element.__delete_lag(self)
            else:
                self.interfaces = [self]

            # Set prev interfaces with current ones
            # Copies interfaces
            self.__prev_interfaces = list(self.interfaces)

        # Set put_port_data
        put_port_data = json.dumps(port_data, sort_keys=True, indent=4)

        # Update Port information
        try:
            response_ports = self.session.s.put(
                uri_ports, verify=False,
                data=put_port_data, proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('PUT', e)

        if not utils._response_ok(response_ports, "PUT"):
            raise GenericOperationError(response_ports.text,
                                        response_ports.status_code)

        # Update values with new ones
        self.get()
        return True
Example #22
0
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing ACL Entry

        :return modified: True if Object was modified and a PUT request was made.
            False otherwise

        '''
        # Variable returned
        modified = False

        acl_entry_data = {}
        acl_entry_data = utils.get_attrs(self, self.config_attrs)

        uri = "{base_url}{class_uri}/{sequence_number}".format(
            base_url=self.session.base_url,
            class_uri=self.base_uri,
            sequence_number=self.sequence_number)

        # Compare dictionaries
        if acl_entry_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:
            post_data = json.dumps(acl_entry_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(uri,
                                              verify=False,
                                              data=post_data,
                                              proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(response.text,
                                            response.status_code)

            else:
                logging.info(
                    "SUCCESS: Update ACL Entry table entry {} succeeded\
                    ".format(self.sequence_number))
            # Set new original attributes
            self.__original_attributes = acl_entry_data

            # Object was modified
            modified = True
        return modified
Example #23
0
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing VRF table entry

        :return modified: True if Object was modified and a PUT request was made.
            False otherwise

        '''
        vrf_data = {}

        vrf_data = utils.get_attrs(self, self.config_attrs)

        uri = "{base_url}{class_uri}/{name}".format(
            base_url=self.session.base_url,
            class_uri=Vrf.base_uri,
            name=self.name)

        # Compare dictionaries
        # if vrf_data == self.__original_attributes:
        if json.dumps(
            vrf_data, sort_keys=True, indent=4) == \
                json.dumps(
                    self.__original_attributes, sort_keys=True, indent=4):
            # Object was not modified
            modified = False

        else:
            post_data = json.dumps(vrf_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(uri,
                                              verify=False,
                                              data=post_data,
                                              proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(response.text,
                                            response.status_code)

            else:
                logging.info("SUCCESS: Adding VRF table entry '%s' succeeded" %
                             self.name)
            # Set new original attributes
            self.__original_attributes = vrf_data
            modified = True
        return modified
Example #24
0
File: vsx.py Project: aruba/pyaoscx
    def update(self):
        '''
        Perform a PUT call to apply changes to an existing VSX inside the switch

        :return modified: True if Object was modified and a PUT request
            was made. False otherwise

        '''

        vsx_data = {}
        vsx_data = utils.get_attrs(self, self.config_attrs)

        # Get VRF uri
        vsx_data["keepalive_vrf"] = self.keepalive_vrf.get_info_format()
        # Get ISL port uri
        vsx_data["isl_port"] = self.isl_port.get_info_format()

        uri = "{base_url}{class_uri}".format(base_url=self.session.base_url,
                                             class_uri=Vsx.base_uri)

        # Compare dictionaries
        if vsx_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:
            post_data = json.dumps(vsx_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(uri,
                                              verify=False,
                                              data=post_data,
                                              proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(response.text,
                                            response.status_code)

            else:
                logging.info("SUCCESS: Adding VSX configuration")
            # Set new original attributes
            self.__original_attributes = vsx_data
            # Object was modified
            modified = True
        return modified
Example #25
0
    def get_next_id(cls, session, parent_static_route):
        '''
        Method used to obtain the ID for the next Static Nexthop. Thus
        Perform a GET call to retrieve all system Static Nexthop inside a
        Static Route, and with it determine the next ID
        :param cls: Object's class
        :param session: pyaoscx.Session object used to represent a logical
            connection to the device
        :param parent_static_route: StaticRoute object, parent for the Static
            Nexthops
        :return new_id: Integer with the new Id for the next Static Nexthop
        '''

        logging.info("Retrieving the switch static_nexthop")

        base_uri = '{base_static_route_uri}/{static_route_name}/static_nexthops'.format(
            base_static_route_uri=parent_static_route.base_uri,
            static_route_name=parent_static_route.reference_address)

        uri = '{base_url}{class_uri}'.format(base_url=session.base_url,
                                             class_uri=base_uri)

        try:
            response = session.s.get(uri, verify=False, proxies=session.proxy)
        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        data = json.loads(response.text)

        next_id = None
        # Get all URI elements in the form of a list
        uri_list = session.api_version.get_uri_from_data(data)

        for uri in uri_list:
            # Obtain ID from uri
            _id, static_nexthop = StaticNexthop.from_uri(
                session, parent_static_route, uri)
            next_id = int(_id)

        # Set next ID
        if next_id is not None:
            next_id += 1
        else:
            next_id = 0
        return next_id
Example #26
0
    def update(self):
        '''
        Perform a PUT call to apply changes to a Device Configuration
        :return modified: Boolean, True if object was modified
        '''

        system_data = {}

        system_data = utils.get_attrs(self, self.config_attrs)

        uri = "{base_url}{class_uri}".format(
            base_url=self.session.base_url,
            class_uri=Configuration.base_uri
        )

        # Compare dictionaries
        if system_data == self.__original_attributes:
            # Object was not modified
            modified = False

        else:

            put_data = json.dumps(system_data, sort_keys=True, indent=4)

            try:
                response = self.session.s.put(
                    uri, verify=False, data=put_data,
                    proxies=self.session.proxy)

            except Exception as e:
                raise ResponseError('PUT', e)

            if not utils._response_ok(response, "PUT"):
                raise GenericOperationError(
                    response.text,
                    response.status_code,
                    "UPDATE SYSTEM ATTRIBUTES")

            else:
                logging.info("SUCCESS: Updating System Attributes")
            # Set new original attributes
            self.__original_attributes = system_data

            # Object was modified, returns True
            modified = True

        return modified
Example #27
0
    def get(self):
        '''
        Perform a GET call to retrieve device attributes
        After data from response, Device class attributes
        are generated using create_attrs()

        '''
        logging.info("Retrieving the switch attributes and capabilities")
        attributes = [
            'software_version',
            'software_images',
            'software_info',
            'platform_name',
            'hostname',
            'boot_time',
            'mgmt_intf_status',
            'aruba_central',
            'capabilities',
            'capacities',
            'admin_password_set',
            'other_config',
            'domain_name'
        ]

        attributes_list = ','.join(attributes)
        uri = "{}system?attributes={}&depth={}".format(
            self.session.base_url, attributes_list,
            self.session.api_version.default_depth)

        try:
            response = self.session.s.get(
                uri, verify=False, proxies=self.session.proxy)

        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        # Load into json format
        data = json.loads(response.text)

        # Create class attributes using util.create_attrs
        utils.create_attrs(self, data)

        # Set device as materialized
        self.materialized = True
Example #28
0
    def get_all(cls, session, parent_ospf_area):
        '''
        Perform a GET call to retrieve all system OSPF Interfaces inside a
        OSPF Area, and create a dictionary containing them as OspfInterface
        objects
        :param cls: Object's class
        :param session: pyaoscx.Session object used to represent a logical
            connection to the device
        :param parent_ospf_area: parent OspfArea object where OspfInterface object
            is stored
        :return: Dictionary containing OSPF Interface IDs as keys and a
            OspfInterface objects as values
        '''

        logging.info("Retrieving the switch OSPF Interfaces of an OSPF area")

        base_uri = '{base_ospf_area_uri}/{ospf_area_area_id}/ospf_interfaces'.format(
            base_ospf_area_uri=parent_ospf_area.base_uri,
            ospf_area_area_id=parent_ospf_area.area_id)

        uri = '{base_url}{class_uri}'.format(base_url=session.base_url,
                                             class_uri=base_uri)

        try:
            response = session.s.get(uri, verify=False, proxies=session.proxy)
        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        data = json.loads(response.text)

        ospf_interface_dict = {}
        # Get all URI elements in the form of a list
        uri_list = session.api_version.get_uri_from_data(data)

        for uri in uri_list:
            # Create a OspfInterface object
            interface_name, ospf_interface = OspfInterface.from_uri(
                session, parent_ospf_area, uri)
            # Load all OSPF Interfaces data from within the Switch
            ospf_interface.get()
            ospf_interface_dict[interface_name] = ospf_interface

        return ospf_interface_dict
Example #29
0
    def get_all(cls, session, parent_acl):
        '''
        Perform a GET call to retrieve all system ACL Entries inside an ACL,
        and create a dictionary containing them
        :param cls: Object's class
        :param session: pyaoscx.Session object used to represent a logical
            connection to the device
        :param parent_acl: parent Acl object where ACL Entry is stored
        :return acl_entry_dict: Dictionary containing ACL Entry IDs as keys and an ACL Entry
            objects as values
        '''

        logging.info("Retrieving all ACL entries within switch for ACL")
        # Set URI
        base_uri = '{base_acl_uri}/{id1}{separator}{id2}/cfg_aces'.format(
            base_acl_uri=parent_acl.base_uri,
            id1=parent_acl.name,
            separator=session.api_version.compound_index_separator,
            id2=parent_acl.list_type)

        uri = '{base_url}{class_uri}'.format(base_url=session.base_url,
                                             class_uri=base_uri)

        try:
            response = session.s.get(uri, verify=False, proxies=session.proxy)
        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        data = json.loads(response.text)

        acl_entry_dict = {}
        # Get all URI elements in the form of a list
        uri_list = session.api_version.get_uri_from_data(data)

        for uri in uri_list:
            # Create a AclEntry object and adds it to parent acl list
            sequence_number, acl_entry = AclEntry.from_uri(
                session, parent_acl, uri)
            # Load all acl_entry data from within the Switch
            acl_entry.get()
            acl_entry_dict[sequence_number] = acl_entry

        return acl_entry_dict
Example #30
0
    def get_all(cls, session, parent_static_route):
        '''
        Perform a GET call to retrieve all system Static Nexthop related to a Static Route ,
        and create a dictionary containing StaticNexthop objects.
        :param cls: Object's class
        :param session: pyaoscx.Session object used to represent a logical
            connection to the device
        :param parent_static_route: StaticRoute object, parent for the Static
            Nexthops
        :return: Dictionary containing Static Nexthop IDs as keys and a Static
            NexthopThis objects as values
        '''

        logging.info("Retrieving the switch static_nexthop")

        base_uri = '{base_static_route_uri}/{static_route_name}/static_nexthops'.format(
            base_static_route_uri=parent_static_route.base_uri,
            static_route_name=parent_static_route.reference_address)

        uri = '{base_url}{class_uri}'.format(base_url=session.base_url,
                                             class_uri=base_uri)

        try:
            response = session.s.get(uri, verify=False, proxies=session.proxy)
        except Exception as e:
            raise ResponseError('GET', e)

        if not utils._response_ok(response, "GET"):
            raise GenericOperationError(response.text, response.status_code)

        data = json.loads(response.text)

        static_nexthop_dict = {}
        # Get all URI elements in the form of a list
        uri_list = session.api_version.get_uri_from_data(data)

        for uri in uri_list:
            # Create a StaticNexthop object and adds it to parent static_route
            # list
            _id, static_nexthop = StaticNexthop.from_uri(
                session, parent_static_route, uri)
            # Load all Static Nexthop data from within the Switch
            static_nexthop.get()
            static_nexthop_dict[_id] = static_nexthop

        return static_nexthop_dict