def main():
    if "CENTRAL_ACCOUNT" in os.environ:
        account = os.environ["CENTRAL_ACCOUNT"]
    else:
        logger.error(
            "CENTRAL_ACCOUNT environment variables is not set. Please set with the account profile used in the config (config.yaml) file. Please see README.md file."
        )
        sys.exit(1)

    if "CENTRAL_REGION" in os.environ:
        region = os.environ["CENTRAL_REGION"]
    else:
        logger.error(
            "CENTRAL_REGION environment variables is not set. Please set with the account profile used in the config (config.yaml) file. Please see README.md file."
        )
        sys.exit(1)

    logger.info(f"ACCOUNT: {account} REGION:{region}")

    # group_name = "greendots/20:4c:03:12:33:20"
    if len(sys.argv) > 1:
        group_name = sys.argv[1]
    else:
        print(
            "Group name is not set. \n show_committed.py GROUP_NAME|GROUP_NAME/MAC.\nSee README.md"
        )
        sys.exit(1)

    # Open file and grab the token
    with open(r"config/config.yaml") as file:
        configfile = yaml.load(file, Loader=yaml.FullLoader)

    central_info = configfile[account]
    region_url = configfile["regions"][region]

    central = ArubaCentralBase(central_info=central_info, ssl_verify=True)

    logger.debug(f"token {central.getToken()['access_token']}:")

    # config_path for AOS10, group_name for all others. May be interchangable.
    # params = {"config_path": "/md/XXV-SEATTLE"}
    # params = {"group_name": group_name }

    token = central.loadToken()
    apiPath = "/caasapi/v1/showcommand/object/committed"

    response = getapi.APICall(central=central,
                              token=token,
                              url=region_url,
                              apiPath=apiPath,
                              reqtype="get",
                              group_name=group_name)
    pprint(response.getData(), indent=2)
Пример #2
0
def get_config(account, ttl_hash=None):
    del ttl_hash  # to emphasize we don't use it and to shut pylint up
    global storedaccount
    storedaccount = account
    # One day we will use this to cache the config
    # account_name = {
    #     "storedaccount": storedaccount,
    # }
    # cachefile = ".cache/caascache.json"
    # Path(".cache").mkdir(parents=True, exist_ok=True)
    # cachefile = Path(cachefile)
    # if cachefile.is_file():
    #     with open(cachefile, "r") as file:
    #         token = file.read()
    # else:
    #     cachefile.touch(exist_ok=True)
    #     with open(cachefile, "w+") as cache:
    #         json.dump(account_name, cache)
    central_info = configfile[storedaccount]
    # Grab the calling function so we can use it for testing
    calling_function = list()
    calling_function.append(inspect.stack()[1][3])
    calling_function.append(test_dir)

    if account == "tests":
        # Send name of calling function to pull test json file
        central = central_test(calling_function)
    else:
        central = ArubaCentralBase(central_info=central_info, ssl_verify=True, logger=logger)

    return central
Пример #3
0
def get_conn_from_file(account_name, logger: MyLogger = log):
    """Creates an instance of class`pycentral.ArubaCentralBase` based on the information
    provided in the YAML/JSON file. \n
        * keyword central_info: A dict containing arguments as accepted by class`pycentral.ArubaCentralBase` \n
        * keyword ssl_verify: A boolean when set to True, the python client validates Aruba Central's SSL certs. \n
        * keyword token_store: Optional. Defaults to None. \n

    :param filename: Name of a JSON/YAML file containing the keywords required for class:`pycentral.ArubaCentralBase`
    :type filename: str
    :return: An instance of class:`pycentral.ArubaCentralBase` to make API calls and manage access tokens.
    :rtype: class:`pycentral.ArubaCentralBase`
    """
    conn = None
    if account_name not in config.data:
        exit(f"exiting... {account_name} missing from {config.file}")
    central_info = config.data[account_name]
    token_store = config.get("token_store", DEFAULT_TOKEN_STORE)
    ssl_verify = config.get("ssl_verify", True)

    conn = ArubaCentralBase(central_info=central_info,
                            token_store=token_store,
                            ssl_verify=ssl_verify,
                            logger=logger
                            )
    return conn
Пример #4
0
def get_conn_from_file(filename, account=None):
    """Creates an instance of class`pycentral.ArubaCentralBase` based on the information
    provided in the YAML/JSON file. \n
        * keyword central_info: A dict containing arguments as accepted by class`pycentral.ArubaCentralBase` \n
        * keyword ssl_verify: A boolean when set to True, the python client validates Aruba Central's SSL certs. \n
        * keyword token_store: Optional. Defaults to None. \n

    :param filename: Name of a JSON/YAML file containing the keywords required for class:`pycentral.ArubaCentralBase` 
    :type filename: str
    :return: An instance of class:`pycentral.ArubaCentralBase` to make API calls and manage access tokens.
    :rtype: class:`pycentral.ArubaCentralBase`
    """
    conn = None
    token_store = None
    ssl_verify = True

    input_args = get_file_contents(filename=filename)
    # Removed hard code "central_info" with variable called account and replaced with
    #  variable that can be passed to method.
    # Set account to "central_info" if None to maintain backward compatibility
    if account is None:
        account = "central_info"
    if account not in input_args:
        sys.exit("exiting... Provide %s in the file %s" % (account, filename))
    central_info = input_args[account]

    if "token_store" in input_args:
        token_store = input_args["token_store"]
    if "ssl_verify" in input_args:
        ssl_verify = input_args["ssl_verify"]

    conn = ArubaCentralBase(central_info=central_info,
                            token_store=token_store,
                            ssl_verify=ssl_verify)
    return conn
Пример #5
0
def get_conn_from_file(filename):
    """Creates an instance of class`pycentral.ArubaCentralBase` based on the information
    provided in the YAML/JSON file. \n
        * keyword central_info: A dict containing arguments as accepted by class`pycentral.ArubaCentralBase` \n
        * keyword ssl_verify: A boolean when set to True, the python client validates Aruba Central's SSL certs. \n
        * keyword token_store: Optional. Defaults to None. \n

    :param filename: Name of a JSON/YAML file containing the keywords required for class:`pycentral.ArubaCentralBase` 
    :type filename: str
    :return: An instance of class:`pycentral.ArubaCentralBase` to make API calls and manage access tokens.
    :rtype: class:`pycentral.ArubaCentralBase`
    """
    conn = None
    token_store = None
    ssl_verify = True

    input_args = get_file_contents(filename=filename)
    if "central_info" not in input_args:
        sys.exit("exiting... Provide central_info in the file %s" % filename)
    central_info = input_args["central_info"]

    if "token_store" in input_args:
        token_store = input_args["token_store"]
    if "ssl_verify" in input_args:
        ssl_verify = input_args["ssl_verify"]

    conn = ArubaCentralBase(central_info=central_info,
                            token_store=token_store,
                            ssl_verify=ssl_verify)
    return conn
Пример #6
0
def get_conn_from_file(filename, account=None, logger=None):
    """Creates an instance of class`pycentral.ArubaCentralBase` based on the information
    provided in the YAML/JSON file. \n
        * keyword central_info: A dict containing arguments as accepted by class`pycentral.ArubaCentralBase` \n
        * keyword ssl_verify: A boolean when set to True, the python client validates Aruba Central's SSL certs. \n
        * keyword token_store: Optional. Defaults to None. \n

    :param filename: Name of a JSON/YAML file containing the keywords required for class:`pycentral.ArubaCentralBase`
    :type filename: str
    :param logger: Provide an instance of class:`logging.logger`, defaults to logger class with name "ARUBA_BASE".
    :type logger: class:`logging.logger`, optional
    :return: An instance of class:`pycentral.ArubaCentralBase` to make API calls and manage access tokens.
    :rtype: class:`pycentral.ArubaCentralBase`
    """
    conn = None
    token_store = None
    ssl_verify = True

    input_args = get_file_contents(filename=filename, logger=logger)
    if not input_args:
        sys.exit("Unable to get the file content... exiting!")
    # if "central_info" not in input_args:
    #     sys.exit("exiting... Provide central_info in the file %s" % filename)
    # central_info = input_args["central_info"]

    if account is None:
        account = "central_info"
    if account not in input_args:
        sys.exit("exiting... Provide %s in the file %s" % (account, filename))
    central_info = input_args[account]

    if "token_store" in input_args:
        token_store = input_args["token_store"]
    if "ssl_verify" in input_args:
        ssl_verify = input_args["ssl_verify"]

    conn = ArubaCentralBase(central_info=central_info,
                            token_store=token_store,
                            ssl_verify=ssl_verify,
                            logger=logger)
    return conn
Пример #7
0
3. ssl_verify:
        To disable Python Client to validate SSL certs, set ssl_verify to False. By default, set to True.

        ssl_verify = True
"""

# Import Aruba Central Base
from pycentral.base import ArubaCentralBase
from pprint import pprint

# Create an instance of ArubaCentralBase using API access token
# or API Gateway credentials.
central_info = {
    "base_url": "<api-gateway-domain-url>",
    "token": {
        "access_token": "<api-gateway-access-token>"
    }
}
ssl_verify = True
central = ArubaCentralBase(central_info=central_info, ssl_verify=ssl_verify)

# Sample API call using 'ArubaCentralBase.command()'
# GET groups from Aruba Central
apiPath = "/configuration/v2/groups"
apiMethod = "GET"
apiParams = {"limit": 20, "offset": 0}
base_resp = central.command(apiMethod=apiMethod,
                            apiPath=apiPath,
                            apiParams=apiParams)
pprint(base_resp)
Пример #8
0
def main():
    logging.basicConfig(
        format="%(asctime)s - %(name)s — %(levelname)s - %(message)s",
        level=logging.WARNING,
    )
    logging.getLogger("ARUBA_BASE").setLevel(logging.WARNING)
    logger = logging.getLogger(__name__)

    if "CENTRAL_ACCOUNT" in os.environ:
        account = os.environ["CENTRAL_ACCOUNT"]
    else:
        logger.error(
            "CENTRAL_ACCOUNT environment variables is not set. Please set with the account profile used in the config (config.yaml) file. Please see README.md file."
        )
        sys.exit(1)

    if "CENTRAL_REGION" in os.environ:
        region = os.environ["CENTRAL_REGION"]
    else:
        logger.error(
            "CENTRAL_REGION environment variables is not set. Please set with the account profile used in the config (config.yaml) file. Please see README.md file."
        )
        sys.exit(1)

    logger.info(f"ACCOUNT: {account} REGION:{region}")

    # group_name = "greendots/20:4c:03:12:33:20"
    group_name = sys.argv[2]

    with open(sys.argv[1], "rb") as pf:
        payload = json.load(pf)

    # Open file and grab the token
    with open(r"config/config.yaml") as file:
        configfile = yaml.load(file, Loader=yaml.FullLoader)

    central_info = configfile[account]
    region_url = configfile["regions"][region]

    central = ArubaCentralBase(central_info=central_info, ssl_verify=True)
    logger.debug(f"token {central.getToken()['access_token']}:")

    # CLI command to send
    # payload = (
    #     '{"cli_cmds": ["vlan 879", "description \'This is API description\'", "!"]}'
    # )

    # Another example of a CLI command - multi-line
    # payload =  {
    #     "cli_cmds": [
    #         "netdestination test-api-alias",
    #         "host 1.2.3.4",
    #         "!",
    #         "ip access-list session test-api-acl",
    #         "alias test-api-alias any any permit",
    #         "!"
    #         ]
    # }

    # config_path for AOS10, group_name for all others. May be interchangable.
    # params = {"config_path": "/md/XXV-SEATTLE"}

    token = central.loadToken()
    apiPath = "/caasapi/v1/exec/cmd"


    response = getapi.APICall(central = central, token = token, url = region_url, apiPath = apiPath, reqtype="post", group_name = group_name, payload = payload)
    # pprint(response.getData(), indent=2)
    print(response.getData()['_global_result']['status_str'])
        To disable Python Client to validate SSL certs, set ssl_verify to False. By default, set to True.

        ssl_verify = True
"""

# Import Aruba Central Base
from pycentral.base import ArubaCentralBase
from pprint import pprint

# Create an instance of ArubaCentralBase using API access token
# or API Gateway credentials.
central_info = {
    "base_url": "<api-gateway-domain-url>",
    "token": {
        "access_token": "<api-gateway-access-token>"
    }
}
ssl_verify = True
central = ArubaCentralBase(central_info=central_info,
                           token_store=None,
                           ssl_verify=ssl_verify)

# Sample API call using Configuration sub-module `pycentral.configuration`
from pycentral.configuration import Groups

# Get groups max limit 20, apply offset and fetch other groups in loop
g = Groups()

module_resp = g.get_groups(central)
pprint(module_resp)
Пример #10
0
 def __init__(self, central_info, ssl_verify=True):
     self.central_info = central_info
     self.ssl_verify = ssl_verify
     self.central = ArubaCentralBase(central_info=self.central_info,
                                     ssl_verify=self.ssl_verify)
Пример #11
0
class ArubaCentral:
    """
    This class allows to get various information from Aruba Central
    """
    def __init__(self, central_info, ssl_verify=True):
        self.central_info = central_info
        self.ssl_verify = ssl_verify
        self.central = ArubaCentralBase(central_info=self.central_info,
                                        ssl_verify=self.ssl_verify)

    # Unable to test without APs online
    def get_ap_status(self, serial_number):
        """
        Is the device reachable (up/down)?
        https://developer.arubanetworks.com/aruba-central/reference/ap-3#apiexternal_controllerget_aps_v2-2
        :param macaddr: String, MAC address of the AP
        :return: Status of the AP
        """
        apiPath = "/monitoring/v2/aps"
        apiMethod = "GET"
        apiParams = {
            "macaddr": serial_number,
            "fields": "status"
        }
        # TODO: determine how to reach the status of the AP
        response = self.central.command(apiMethod=apiMethod,
                                   apiPath=apiPath,
                                   apiParams=apiParams)["aps"][serial_number]["status"]
        return response

    #Tested
    def get_template(self, serial_number):
        """
        Identifying which templates are assigned to devices
        https://developer.arubanetworks.com/aruba-central/reference/devices-4#apidevicesget_devices_template_details-1
        :param serial_number: Serial number of the device
        :return: Template name assigned to the device
        """
        apiPath = "/configuration/v1/devices/template"
        apiMethod = "GET"
        apiParams = {
            "device_serials": serial_number
        }

        response = self.central.command(apiMethod=apiMethod,
                                   apiPath=apiPath,
                                   apiParams=apiParams)['msg']['data'][serial_number]['template_name']

        return response

    # Failed test. Output: {'code': 500, 'msg': {'description': 'Internal Server Error', 'error_code': '0001', 'service_name': 'Configuration'}}
    def get_template_info(self, serial_number):
        """
        Retrieve the content of the templates (rendered)
        https://developer.arubanetworks.com/aruba-central/reference/devices-4#apidevicesget_device_variabilised_template-1
        :param serial_number: Serial number of the device
        :return: Variablised template of the device
        """
        api_path = f"/configuration/v1/devices/{serial_number}/variablised_template"
        api_method = "GET"

        response = self.central.command(apiMethod=api_method,
                                   apiPath=api_path)
        return response

    # Tested
    def get_template_sync_status(self, serial_number):
        """
        Is the device synchronised with the template
        https://developer.arubanetworks.com/aruba-central/reference/devices-4#apidevicesget_device_configuration_details-1
        :param serial_number: Serial number of the device
        :return: Template error status (True or False)
        """
        api_path = f"/configuration/v1/devices/{serial_number}/config_details"
        api_method = "GET"
        api_params = {"details":"false"}
        headers = {"Accept": "application/json"}
        response = self.central.command(apiMethod=api_method,
                                   apiPath=api_path,
                                   apiParams=api_params, headers=headers)['msg']

        start = response.find('{')
        stop = response.find('}') + 1
        template_error_status = json.loads(response[start:stop])['Template_error_status']

        return template_error_status

    # This information is to be retrieved directly from the switch (using switch management IP address). Not completed.
    def get_connected_lldp_device(self, switch_ip, port_name):
        """
        Identifying which devices is connected to the trunk via LLDP
        https://developer.arubanetworks.com/aruba-aoscx/reference#get_system-interfaces-name-lldp-neighbors
        :param switch_ip: IP address of the switch
        :param port_name: Interface name. Should be alphanumeric and no more than about 8 bytes long.
        May be the same as the port name, for non-bonded ports.
        Must otherwise be unique among the names of ports, interfaces, and bridges on a host.
        :return:
        """
        api_path = f"https://{switch_ip}/rest/v10.04/system/interfaces/{port_name}/lldp_neighbors"
        headers = {"Accept": "application/json"}
        response = requests.request("GET", api_path, headers=headers)

        return response.text

    # Unable to test without SSID being broadcasted
    def get_ssid_broadcasted(self):
        """
        Which SSID are being broadcasted.
        https://developer.arubanetworks.com/aruba-central/reference/ssids-2
        :return:
        """
        #
        api_path = "/rapids/v1/ssid_allow"
        api_method = "GET"
        api_params = {
            "limit": 20,
            "offset": 0
        }

        response = self.central.command(apiMethod=api_method,
                                    apiPath=api_path,
                                    apiParams=api_params)
        return response

    # Test method
    def _test(self):
        """
        Test API call.
        :return: Sample response: {'code': 200, 'msg': {'data': [['Access Switches'],
        ['Core Switches'], ['default'], ['unprovisioned']], 'total': 4}}
        """
        api_path = "/configuration/v2/groups"
        api_method = "GET"
        api_params = {
            "limit": 20,
            "offset": 0
        }

        response = self.central.command(apiMethod=api_method,
                                    apiPath=api_path,
                                    apiParams=api_params)
        return response

    # Test method
    def _test_networks(self):
        """
        Test API call.
        :return: Sample response: {'code': 200, 'msg': {'data': [['Access Switches'],
        ['Core Switches'], ['default'], ['unprovisioned']], 'total': 4}}
        """
        api_path = "/monitoring/v2/networks"
        api_method = "GET"
        api_params = {
            "limit": 20,
            "offset": 0
        }

        response = self.central.command(apiMethod=api_method,
                                    apiPath=api_path,
                                    apiParams=api_params)
        return response