Ejemplo n.º 1
0
def create_first_password(base_url, password=None):
    """
    Perform POST and PUT calls to open a restricted session with user admin and create the first password needed to gain access to other API calls.

    :param base_url: URL in main() function
    :param password: password
    :return: requests.session object with loaded cookie jar
    """
    if password is None:
        password = getpass.getpass(prompt='Please provide a password: '******'ERROR: Error connecting to host: connection attempt timed out.')
        exit(-1)
Ejemplo n.º 2
0
def add_l2_port(port_name, port_desc=None, port_admin_state="up", **kwargs):
    """
    Perform a POST call to create a Port table entry for physical L2 interface.  If the Port table entry exists, this
    function will perform a PUT call to update the entry with the given parameters.

    :param port_name: Alphanumeric Port name
    :param port_desc: Optional description for the interface. Defaults to nothing if not specified.
    :param port_admin_state: Optional administratively-configured state of the port.
        Defaults to "up" if not specified
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    ports_list = get_all_ports(**kwargs)

    port_name_percents = common_ops._replace_special_characters(port_name)
    port_data = {
        "admin": port_admin_state,
        "interfaces": ["/rest/v1/system/interfaces/%s" % port_name_percents],
        "name": port_name,
        "routing": False
    }

    if port_desc is not None:
        port_data['description'] = port_desc

    if "/rest/v1/system/ports/%s" % port_name_percents not in ports_list:
        target_url = kwargs["url"] + "system/ports"
        payload_data = json.dumps(port_data, sort_keys=True, indent=4)
        response = kwargs["s"].post(target_url,
                                    data=payload_data,
                                    verify=False)

        if not common_ops._response_ok(response, "POST"):
            logging.warning(
                "FAIL: Adding Port table entry '%s' failed with status code %d: %s"
                % (port_name, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Adding Port table entry '%s' succeeded" %
                         port_name)
            return True
    else:
        target_url = kwargs["url"] + "system/ports/%s" % port_name_percents
        port_data.pop(
            'name', None
        )  # must remove this item from the json since name can't be modified
        payload_data = json.dumps(port_data, sort_keys=True, indent=4)
        response = kwargs["s"].put(target_url, data=payload_data, verify=False)

        if not common_ops._response_ok(response, "PUT"):
            logging.warning(
                "FAIL: Updating Port table entry '%s' failed with status code %d: %s"
                % (port_name, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Updating Port table entry '%s' succeeded" %
                         port_name)
            return True
Ejemplo n.º 3
0
Archivo: nae.py Proyecto: k1z2/pyaoscx
def get_all_nae_agents_of_script(script_name, params={}, **kwargs):
    """
    Perform a GET call to get a list or dictionary of Network Analytics Engine agents for the specified NAE script.

    :param script_name: Alphanumeric String of the name of the script
    :param params: Dictionary of optional parameters for the GET request
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: List (v1) or Dictionary (v10.04 or empty) containing all of the existing agents for the specified script.
    """
    target_url = kwargs[
        "url"] + "system/nae_scripts/%s/nae_agents" % script_name
    response = kwargs["s"].get(target_url, params=params, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting list/dictionary of all NAE agents for NAE script named %s failed with "
            "status code %d: %s" %
            (script_name, response.status_code, response.text))
        all_nae_agents = {}
    else:
        if kwargs["url"].endswith("/v1/"):
            logging.info(
                "SUCCESS: Getting list of all NAE agents for script named %s on device succeeded"
                % script_name)
        else:
            # Else logic designed for v10.04 and later
            logging.info(
                "SUCCESS: Getting dictionary of all NAE agents for script named %s on device succeeded"
                % script_name)
        all_nae_agents = response.json()

    return all_nae_agents
Ejemplo n.º 4
0
    def _get_json_configuration(self,
                                checkpoint="running-config",
                                params={},
                                **kwargs):
        """
        Perform a GET call to retrieve a configuration file based off of the checkpoint name

        :param checkpoint: String name of the checkpoint configuration
        :param params: Dictionary of optional parameters for the GET request
        :param kwargs:
            keyword s: requests.session object with loaded cookie jar
            keyword url: URL in main() function
        :return: JSON format of the configuration
        """

        target_url = kwargs["url"] + "fullconfigs/{}".format(checkpoint)

        response = kwargs["s"].get(target_url, params=params, verify=False)

        if not common_ops._response_ok(response, "GET"):
            logging.warning(
                "FAIL: Getting configuration checkpoint named %s failed with status code %d: %s"
                % (checkpoint, response.status_code, response.text))
            configuration_json = {}
        else:
            logging.info(
                "SUCCESS: Getting configuration checkpoint named %s succeeded"
                % checkpoint)
            configuration_json = response.json()

        return configuration_json
Ejemplo n.º 5
0
    def _get_resource_utilization(self, params={}, **kwargs):
        """
        Perform a GET call to get the cpu, memory, and open_fds of the switch
        Note that this works for physical devices, not an OVA.

        :param params: Dictionary of optional parameters for the GET request
        :param kwargs:
            keyword s: requests.session object with loaded cookie jar
            keyword url: URL in main() function
        :return: Dictionary containing resource utilization information
        """

        target_url = kwargs["url"] + "system/subsystems/management_module/*"

        response = kwargs["s"].get(target_url, params=params, verify=False)

        if not common_ops._response_ok(response, "GET"):
            logging.warning(
                "FAIL: Getting dictionary of resource utilization info failed with status code %d: %s"
                % (response.status_code, response.text))
            resources_dict = {}
        else:
            logging.info(
                "SUCCESS: Getting dictionary of resource utilization information succeeded"
            )
            resources_dict = response.json()

        return resources_dict
Ejemplo n.º 6
0
def _delete_vni_mapping(vni, **kwargs):
    """
    Perform DELETE call to remove a Virtual Network ID for a VXLAN.

    :param vni: Integer representing the Virtual Network ID
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    vni_list = get_vni_list(**kwargs)

    if "vxlan_vni,%d" % vni in vni_list:
        target_url = kwargs[
            "url"] + "system/virtual_network_ids/vxlan_vni,%d" % vni
        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning(
                "FAIL: Deleting VNI '%s' failed with status code %d: %s" %
                (vni, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Deleting VNI '%s' succeeded" % vni)
            return True
    else:
        logging.info(
            "SUCCESS: No need to delete VNI '%s' since it doesn't exist" % vni)
        return True
Ejemplo n.º 7
0
def _update_acl(list_name, list_type, **kwargs):
    """
    Perform a PUT call to version-up an ACL. This is required whenever entries of an ACL are changed
    in any way.

    :param list_name: Alphanumeric name of the ACL
    :param list_type: Type should be one of "ipv4," "ipv6," or "mac"
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """

    acl_data = get_acl(list_name, list_type, **kwargs)
    acl_key = "{},{}".format(list_name, list_type)

    acl_data['cfg_version'] = random.randint(-9007199254740991,
                                             9007199254740991)
    target_url = kwargs["url"] + "system/acls/%s" % acl_key
    put_data = json.dumps(acl_data, sort_keys=True, indent=4)

    response = kwargs["s"].put(target_url, data=put_data, verify=False)

    if not common_ops._response_ok(response, "PUT"):
        logging.warning(
            "FAIL: Updating %s ACL '%s' failed with status code %d: %s" %
            (list_type, list_name, response.status_code, response.text))
        return False
    else:
        logging.info("SUCCESS: Updating %s ACL '%s' succeeded" %
                     (list_type, list_name))
        return True
Ejemplo n.º 8
0
def _get_all_acl_entries(list_name, list_type, **kwargs):
    """
    Perform a GET call to get all entries of an ACL

    :param list_name: Alphanumeric name of the ACL
    :param list_type: Type should be one of "ipv4," "ipv6," or "mac"
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Dictionary containing ACL entry URIs
    """

    target_url = kwargs["url"] + "system/acls/%s,%s/cfg_aces" % (list_name,
                                                                 list_type)

    response = kwargs["s"].get(target_url, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting dictionary of URIS of entries in %s ACL '%s' failed with status code %d: %s"
            % (list_type, list_name, response.status_code, response.text))
    else:
        logging.info(
            "SUCCESS: Getting dictionary of URIs of entries in %s ACL '%s' succeeded"
            % (list_type, list_name))

    acl_entries = response.json()

    # for some reason, this API returns a list when empty, and a dictionary when there is data
    # make this function always return a dictionary,
    if not acl_entries:
        return {}
    else:
        return acl_entries
Ejemplo n.º 9
0
def _create_ospfv3_interface(vrf, ospf_id, area_id, interface_name, **kwargs):
    """
    Perform POST calls to attach an interface to an OSPFv3 area.

    :param vrf: Alphanumeric name of the VRF the OSPFv3 ID belongs to
    :param ospf_id: OSPFv3 process ID between numbers 1-63
    :param area_id: Unique identifier as a string in the form of x.x.x.x
    :param interface_name: Alphanumeric name of the interface that will be attached to the OSPFv3 area
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    interface_name_percents = common_ops._replace_special_characters(interface_name)
    port_uri = '/rest/v10.04/system/interfaces/' + interface_name_percents

    interface_data = {
        "interface_name": interface_name,
        "port": port_uri
    }

    target_url = kwargs["url"] + "system/vrfs/%s/ospfv3_routers/%s/areas/%s/ospf_interfaces" % (vrf, ospf_id, area_id)
    post_data = json.dumps(interface_data, sort_keys=True, indent=4)

    response = kwargs["s"].post(target_url, data=post_data, verify=False)

    if not common_ops._response_ok(response, "POST"):
        logging.warning("FAIL: Applying Interface '%s' to OSPFv3 ID '%s' failed with status code %d: %s"
              % (interface_name, ospf_id, response.status_code, response.text))
        return False
    else:
        logging.info("SUCCESS: Applying Interface '%s' to OSPFv3 ID '%s' succeeded"
              % (interface_name, ospf_id))
        return True
Ejemplo n.º 10
0
def initialize_port_entry(port_name, **kwargs):
    """
    Perform a PUT call on the Port to initialize it to it's default state, then initialize the Interface entry.

    :param port_name: Alphanumeric name of the system port
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    port_name_percents = common_ops._replace_special_characters(port_name)
    port_data = {}
    target_url = kwargs["url"] + "system/ports/%s" % port_name_percents
    put_data = json.dumps(port_data, sort_keys=True, indent=4)

    response = kwargs["s"].put(target_url, data=put_data, verify=False)

    if not common_ops._response_ok(response, "PUT"):
        logging.warning(
            "FAIL: Initializing port '%s' failed with status code %d: %s" %
            (port_name, response.status_code, response.text))
        return False
    else:
        logging.info("SUCCESS: Initializing port '%s' succeeded" % port_name)
        return interface.initialize_interface_entry(port_name, **kwargs)
Ejemplo n.º 11
0
def copy_config(src_config_name, dst_config_name, **kwargs):
    """
    Perform a PUT call to copy contents from one config into another config

    :param src_config_name: Name of config to copy data from
    :param dst_config_name: Name of config to copy data into
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """

    query = {"from": "/rest/v10.04/fullconfigs/%s" % src_config_name}

    target_url = kwargs["url"] + "fullconfigs/%s" % dst_config_name

    response = kwargs["s"].put(target_url, params=query, verify=False)

    if not common_ops._response_ok(response, "PUT"):
        logging.warning("FAIL: Copying config data from '%s' to '%s' failed with status code %d: %s"
              % (src_config_name, dst_config_name, response.status_code, response.text))
        return False
    else:
        logging.info("SUCCESS: Copying config data from '%s' to '%s' succeeded"
              % (src_config_name, dst_config_name))
        return True
Ejemplo n.º 12
0
def _get_vlan(vlan_id, depth=1, selector="writable", **kwargs):
    """
    Perform a GET call to retrieve data for a VLAN table entry

    :param depth: Integer deciding how many levels into the API JSON that references will be returned.
    :param selector: Alphanumeric option to select specific information to return.  The options are 'configuration',
        'status', or 'statistics'.  If running v10.04 or later, an additional option 'writable' is included.
    :param vlan_id: Numeric ID of VLAN
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Dictionary containing port data
    """
    if selector not in ['configuration', 'status', 'statistics', 'writable', None]:
        raise Exception("ERROR: Selector should be 'configuration', 'status', 'statistics', or 'writable'")

    target_url = kwargs["url"] + "system/vlans/%d" % vlan_id
    payload = {
        "depth": depth,
        "selector": selector
    }
    response = kwargs["s"].get(target_url, verify=False, params=payload, timeout=2)
    if not common_ops._response_ok(response, "GET"):
        logging.warning("FAIL: Getting VLAN ID '%d' table entry failed with status code %d: %s"
                        % (vlan_id, response.status_code, response.text))
        output = {}
    else:
        logging.info("SUCCESS: Getting VLAN ID '%d' table entry succeeded" % vlan_id)
        output = response.json()

    return output
Ejemplo n.º 13
0
def _delete_vlan(vlan_id, **kwargs):
    """
    Perform a DELETE call to delete VLAN.

    :param vlan_id: Numeric ID of VLAN
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """

    vlans_dict = get_all_vlans(**kwargs)

    if str(vlan_id) in vlans_dict:

        target_url = kwargs["url"] + "system/vlans/%s" % vlan_id

        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning("FAIL: Deleting VLAN ID: '%s' failed with status code %d: %s"
                            % (vlan_id, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Deleting VLAN ID: '%s' succeeded" % vlan_id)
            return True
    else:
        logging.info("SUCCESS: No need to remove VLAN ID '%d' since it doesn't exist" % vlan_id)
        return True
Ejemplo n.º 14
0
Archivo: nae.py Proyecto: k1z2/pyaoscx
def get_nae_script_code(nae_script, params={}, **kwargs):
    """
    Perform a GET call to get the decoded Network Analytics Engine script from the device.

    :param nae_script: String of name of the script that the function will return
    :param params: Dictionary of optional parameters for the GET request
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: String of NAE script python code, decoded from base64
    """
    target_url = kwargs["url"] + "system/nae_scripts/" + nae_script
    response = kwargs["s"].get(target_url, params=params, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting NAE script %s python code on device failed with status code %d: %s"
            % (nae_script, response.status_code, response.text))
        nae_script_code = ""
    else:
        logging.info(
            "SUCCESS: Getting NAE script %s python code on device succeeded" %
            nae_script)
        nae_script_details = response.json()
        nae_script_code = base64.b64decode(nae_script_details['script'])

    return nae_script_code
Ejemplo n.º 15
0
Archivo: nae.py Proyecto: k1z2/pyaoscx
def get_nae_agent_details(script_name, agent_name, params={}, **kwargs):
    """
    Perform a GET call to get the details of a specific Network Analytics Engine agent on the device.

    :param script_name: Alphanumeric String of the name of the script
    :param agent_name: Alphanumeric String of the name of the agent that will have details returned
    :param params: Dictionary of optional parameters for the GET request
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Dictionary containing the details of the specified NAE script on the device
    """
    target_url = kwargs["url"] + "system/nae_scripts/%s/nae_agents/%s" % (
        script_name, agent_name)
    response = kwargs["s"].get(target_url, params=params, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting details of NAE agent %s for script %s on device failed with status code %d: %s"
            % (agent_name, script_name, response.status_code, response.text))
        nae_script_details = {}
    else:
        logging.info(
            "SUCCESS: Getting details of NAE agent %s for script %s on device succeeded"
            % (agent_name, script_name))
        nae_script_details = response.json()

    return nae_script_details
Ejemplo n.º 16
0
def _update_ospf_interface_type(vrf, ospf_id, interface_name, interface_type, **kwargs):
    """
    Perform PUT calls to update the type of OSPFv2 Interface given, as well as enable routing on the interface

    :param vrf: Alphanumeric name of the VRF the OSPF ID belongs to
    :param ospf_id: OSPF process ID between numbers 1-63
    :param interface_name: Alphanumeric name of the interface that will be attached to the OSPF area
    :param interface_type: Alphanumeric type of OSPF interface.  The options are 'broadcast', 'loopback', 'nbma',
        'none', 'pointomultipoint', 'pointopoint', and 'virtuallink'
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    interface_name_percents = common_ops._replace_special_characters(interface_name)

    interface_data = interface.get_interface(interface_name, depth=1, selector="writable", **kwargs)

    interface_data['ospf_if_type'] = "ospf_iftype_%s" % interface_type
    interface_data['routing'] = True
    interface_data['vrf'] = "/rest/v10.04/system/vrfs/" + vrf

    target_url = kwargs["url"] + "system/interfaces/%s" % interface_name_percents
    put_data = json.dumps(interface_data, sort_keys=True, indent=4)

    response = kwargs["s"].put(target_url, data=put_data, verify=False)

    if not common_ops._response_ok(response, "PUT"):
        logging.warning("FAIL: Updating OSPF %s interface type for Interface '%s' failed with status code %d: %s"
              % (ospf_id, interface_name, response.status_code, response.text))
        return False
    else:
        logging.info("SUCCESS: Updating OSPF %s interface type for Interface '%s' succeeded" % (ospf_id, interface_name))
        return True
Ejemplo n.º 17
0
def create_ospfv3_id(vrf, ospf_id,  **kwargs):
    """
    Perform a POST call to create an OSPFv3 ID

    :param vrf: Alphanumeric name of the VRF the OSPFv3 ID belongs to
    :param ospf_id: OSPF process ID between numbers 1-63
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """

    ospf_data = {
        "instance_tag": ospf_id
    }

    target_url = kwargs["url"] + "system/vrfs/%s/ospfv3_routers" % vrf

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

    response = kwargs["s"].post(target_url, data=post_data, verify=False, timeout=2)

    if not common_ops._response_ok(response, "POST"):
        logging.warning("FAIL: Creating OSPFv3 ID '%s' on VRF %s failed with status code %d: %s"
              % (ospf_id, vrf, response.status_code, response.text))
        return False
    else:
        logging.info("SUCCESS: Creating OSPFv3 ID '%s' succeeded on VRF %s" % (ospf_id, vrf))
        return True
Ejemplo n.º 18
0
def delete_port(port_name, **kwargs):
    """
    Perform a DELETE call to delete a Port table entry.

    :param port_name: Port table entry name
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """

    port_name_percents = common_ops._replace_special_characters(port_name)

    ports_list = get_all_ports(**kwargs)

    if "/rest/v1/system/ports/%s" % port_name_percents in ports_list:

        target_url = kwargs["url"] + "system/ports/%s" % port_name_percents

        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning(
                "FAIL: Deleting Port '%s' failed with status code %d: %s" %
                (port_name, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Deleting Port '%s' succeeded" % port_name)
            return True
    else:
        logging.info(
            "SUCCESS: No need to remove  Port '%s' since it doesn't exist" %
            port_name)
        return True
Ejemplo n.º 19
0
def _delete_ospfv3_id(vrf, ospf_id, **kwargs):
    """
    Perform a DELETE call to delete an OSPFv3 Router ID

    :param vrf: Alphanumeric name of the VRF the OSPFv3 ID belongs to
    :param ospf_id: OSPFv3 process ID between numbers 1-63
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    ospf_list = get_ospfv3_routers(vrf, **kwargs)
    ospf_uri = "/rest/v10.04/system/vrfs/%s/ospfv3_routers/%s" % (vrf, ospf_id)
    ospf_id_key = str(ospf_id)

    if ospf_id_key in ospf_list and ospf_uri == ospf_list[ospf_id_key]:

        target_url = kwargs["url"] + "system/vrfs/%s/ospfv3_routers/%s" % (vrf, ospf_id)

        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning("FAIL: Deleting OSPFv3 ID '%s' on VRF '%s' failed with status code %d: %s"
                  % (ospf_id, vrf, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Deleting OSPFv3 ID %s on VRF '%s' succeeded" % (ospf_id, vrf))
            return True
    else:
        logging.info("SUCCESS: No need to delete OSPFv3 ID %s on VRF '%s' since it doesn't exist"
              % (ospf_id, vrf))
        return True
Ejemplo n.º 20
0
def _delete_ipv6_address(port_name, ip, **kwargs):
    """
    Perform a DELETE call to remove an IPv6 address from an Interface.

    :param port_name: Alphanumeric Interface name
    :param ip: IPv6 address assigned to the interface that will be removed.
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    if ip in interface.get_ipv6_addresses(port_name, **kwargs):
        port_name_percents = common_ops._replace_special_characters(port_name)
        ip_address = common_ops._replace_special_characters(ip)
        target_url = kwargs["url"] + "system/interfaces/%s/ip6_addresses/%s" % (
            port_name_percents, ip_address)

        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning(
                "FAIL: Deleting IPv6 Address '%s' from Port table entry '%s' failed with status code %d: %s"
                % (ip, port_name, response.status_code, response.text))
            return False
        else:
            logging.info(
                "SUCCESS: Deleting IPv6 Address '%s' from Port table entry '%s' succeeded"
                % (ip, port_name))
            return True
    else:
        logging.info(
            "SUCCESS: No need to delete IPv6 Address '%s' from Port table entry '%s' since it does not exist"
            % (ip, port_name))
        return True
Ejemplo n.º 21
0
def _get_acl(list_name, list_type, **kwargs):
    """
    Perform a GET call to get details of a particular ACL

    :param list_name: Alphanumeric name of the ACL
    :param list_type: Type should be one of "ipv4," "ipv6," or "mac"
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Dictionary containing data about a particular ACL
    """
    acl_key = "{},{}".format(list_name, list_type)
    target_url = kwargs[
        "url"] + "system/acls/%s?depth=2&selector=writable" % acl_key

    response = kwargs["s"].get(target_url, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting %s ACL '%s' failed with status code %d: %s" %
            (list_type, list_name, response.status_code, response.text))
    else:
        logging.info("SUCCESS: Getting %s ACL '%s' succeeded" %
                     (list_type, list_name))

    acl = response.json()
    return acl
Ejemplo n.º 22
0
def delete_evpn_instance(**kwargs):
    """
    Perform DELETE calls to remove an EVPN instance

    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """
    current_evpn = get_evpn_info(**kwargs)

    if current_evpn:
        if kwargs["url"].endswith("/v1/"):
            target_url = kwargs["url"] + "system/evpns"
        else:
            # Else logic designed for v10.04 and later
            target_url = kwargs["url"] + "system/evpn"
        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning(
                "FAIL: Deleting EVPN Instance failed with status code %d: %s" %
                (response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Deleting EVPN Instance succeeded")
            return True
    else:
        logging.info(
            "SUCCESS: No need to delete EVPN instance since it doesn't exist")
        return True
Ejemplo n.º 23
0
def _delete_acl_v1(list_name, list_type, **kwargs):
    """
    Perform a DELETE call to delete an ACL

    :param list_name: Alphanumeric name of the ACL
    :param list_type: Type should be one of "ipv4," "ipv6," or "mac"
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: True if successful, False otherwise
    """

    acls_list = get_all_acls(**kwargs)

    if "/rest/v1/system/acls/%s/%s" % (list_name, list_type) in acls_list:

        target_url = kwargs["url"] + "system/acls/%s/%s" % (list_name,
                                                            list_type)

        response = kwargs["s"].delete(target_url, verify=False)

        if not common_ops._response_ok(response, "DELETE"):
            logging.warning(
                "FAIL: Deleting %s ACL '%s' failed with status code %d: %s" %
                (list_type, list_name, response.status_code, response.text))
            return False
        else:
            logging.info("SUCCESS: Deleting %s ACL '%s' succeeded" %
                         (list_type, list_name))
            return True
    else:
        logging.info(
            "SUCCESS: No need to delete %s ACL '%s' since it doesn't exist" %
            (list_type, list_name))
        return True
Ejemplo n.º 24
0
def get_evpn_info(**kwargs):
    """
    Perform a GET call to receive the EVPN information on the system

    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Information
    """
    if kwargs["url"].endswith("/v1/"):
        target_url = kwargs["url"] + "system/evpns"
    else:
        # Else logic designed for v10.04 and later
        target_url = kwargs["url"] + "system/evpn"

    response = kwargs["s"].get(target_url, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.info(
            "SUCCESS: Getting EVPN information replied with status code %d, no EVPN information exists"
            % response.status_code)
        evpn_info = []
    else:
        logging.info("SUCCESS: Getting EVPN information succeeded")
        evpn_info = response.json()

    return evpn_info
Ejemplo n.º 25
0
    def _get_power_supplies(self, params={}, **kwargs):
        """
        Perform a GET call to get the power supply information of the switch
        Note that this works for physical devices, not an OVA.

        :param params: Dictionary of optional parameters for the GET request
        :param kwargs:
            keyword s: requests.session object with loaded cookie jar
            keyword url: URL in main() function
        :return: Dictionary containing power supply information
        """

        target_url = kwargs["url"] + "system/subsystems/*/*/power_supplies/*"

        response = kwargs["s"].get(target_url, params=params, verify=False)

        if not common_ops._response_ok(response, "GET"):
            logging.warning(
                "FAIL: Getting dictionary of PSU information failed with status code %d: %s"
                % (response.status_code, response.text))
            temp_info_dict = {}
        else:
            logging.info(
                "SUCCESS: Getting dictionary of PSU information succeeded")
            temp_info_dict = response.json()

        return temp_info_dict
Ejemplo n.º 26
0
def login(base_url, username=None, password=None):
    """

    Perform a POST call to login and gain access to other API calls.
    If either username or password is not specified, user will be prompted to enter the missing credential(s).

    :param base_url: URL in main() function
    :param username: username
    :param password: password
    :return: requests.session object with loaded cookie jar
    """
    if username is None and password is None:
        username = input('Enter username: '******'ERROR: Error connecting to host: connection attempt timed out.')
        exit(-1)
    # Response OK check needs to be passed "PUT" since this POST call returns 200 instead of conventional 201
    if not common_ops._response_ok(response, "PUT"):
        logging.warning("FAIL: Login failed with status code %d: %s" %
                        (response.status_code, response.text))
        exit(-1)
    else:
        logging.info("SUCCESS: Login succeeded")
        return s
Ejemplo n.º 27
0
    def _get_ntp_associations(self, params={}, **kwargs):
        """
        Perform a GET call to get the NTP associations across all VRFs

        :param params: Dictionary of optional parameters for the GET request
        :param kwargs:
            keyword s: requests.session object with loaded cookie jar
            keyword url: URL in main() function
        :return: Dictionary containing all of the NTP associations on the switch
        """

        target_url = kwargs["url"] + "system/vrfs/*/ntp_associations"

        response = kwargs["s"].get(target_url, params=params, verify=False)

        associations_dict = {}
        for server_uri in response:
            server_name = server_uri[(server_uri.rfind('/') +
                                      1):]  # Takes string after last '/'
            associations_dict[server_name] = {}

        if not common_ops._response_ok(response, "GET"):
            logging.warning(
                "FAIL: Getting dictionary of resource utilization info failed with status code %d: %s"
                % (response.status_code, response.text))
            associations_dict = {}
        else:
            logging.info(
                "SUCCESS: Getting dictionary of resource utilization information succeeded"
            )
            associations_dict = response.json()

        return associations_dict
Ejemplo n.º 28
0
def get_system_info(params={}, **kwargs):
    """
    Perform a GET call to get system information

    :param params: Dictionary of optional parameters for the GET request
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Dictionary containing system information
    """
    target_url = kwargs["url"] + "system"

    response = kwargs["s"].get(target_url, params=params, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting dictionary of system information failed with status code %d: %s"
            % (response.status_code, response.text))
        system_info_dict = {}
    else:
        logging.info(
            "SUCCESS: Getting dictionary of system information succeeded")
        system_info_dict = response.json()

    return system_info_dict
Ejemplo n.º 29
0
def get_product_info(params={}, **kwargs):
    """
    Perform a GET call to get the product information, such as MAC, Part Number, Model, and Serial

    :param params: Dictionary of optional parameters for the GET request
    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: Dictionary containing product information
    """

    if kwargs["url"].endswith("/v1/"):
        target_url = kwargs["url"] + "/system/subsystems/chassis/1?attributes=product_info"
    else:
        # Else logic designed for v10.04 and later
        target_url = kwargs["url"] + "/system/subsystems/chassis,1?attributes=product_info"

    response = kwargs["s"].get(target_url, params=params, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning("FAIL: Getting dictionary of product information failed with status code %d: %s"
              % (response.status_code, response.text))
        product_info_dict = {}
    else:
        logging.info("SUCCESS: Getting dictionary of product information succeeded")
        product_info_dict = response.json()

    return product_info_dict
Ejemplo n.º 30
0
def get_all_lldp_neighbors(**kwargs):
    """
    Perform a GET call to get a list of all entries in the lldp_neighbors table.  This is currently only supported in
    v1, so even a v10.04 or later AOS-CX device will use the v1 REST call.

    :param kwargs:
        keyword s: requests.session object with loaded cookie jar
        keyword url: URL in main() function
    :return: List of all lldp_neighors in the table
    """
    target_url = kwargs["url"] + "system/interfaces/*/lldp_neighbors"

    if not kwargs["url"].endswith("/v1/"):
        target_url = target_url.replace('v10.04', 'v1')

    response = kwargs["s"].get(target_url, verify=False)

    if not common_ops._response_ok(response, "GET"):
        logging.warning(
            "FAIL: Getting list of all lldp_neighbors entries failed with status code %d: %s"
            % (response.status_code, response.text))
        lldp_neighbors_list = []
    else:
        logging.info(
            "SUCCESS: Getting list of all lldp_neighbors entries succeeded")
        lldp_neighbors_list = response.json()

    return lldp_neighbors_list