Esempio n. 1
0
    def get_device_config_list(self, device_type):
        """Get the config status of a list of devices.  When 'all' is specified, it concatenats
            the vedges and controller together to provide a single method to retrieve status
            in the same way as get_device_status_list.

        Args:
            device_type (str): 'vedges', 'controllers', or 'all'

        Returns:
            result (list): All data associated with a response.
        """

        if device_type.lower() == 'all':
            # Get vedges
            url = f"{self.base_url}system/device/vedges"
            response = HttpMethods(self.session, url).request('GET')
            vedge_results = ParseMethods.parse_data(response)

            #Get controllers
            url = f"{self.base_url}system/device/controllers"
            response = HttpMethods(self.session, url).request('GET')
            result = ParseMethods.parse_data(response)
            controller_results = ParseMethods.parse_data(response)

            return controller_results + vedge_results

        url = f"{self.base_url}system/device/{device_type}"
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)

        return result
    def update_device_template(self, device_template):
        """Update a single device template to Vmanage.


        Args:
            device_template (dict): Device Template

        Returns:
            result (list): Response from Vmanage

        """
        #
        # File templates are much easier in that they are just a bunch of CLI
        #
        if device_template['configType'] == 'file':
            url = f"{self.base_url}template/device/cli/{device_template['templateId']}"
            response = HttpMethods(self.session, url).request(
                'PUT', payload=json.dumps(device_template))
        #
        # Feature based templates are just a list of templates Id that make up a devie template.  We are
        # given the name of the feature templates, but we need to translate that to the template ID
        #
        else:
            if 'generalTemplates' in device_template:
                device_template[
                    'generalTemplates'] = self.generalTemplates_to_id(
                        device_template['generalTemplates'])
            else:
                raise Exception("No generalTemplates found in device template",
                                data=device_template)
            url = f"{self.base_url}template/device/feature/{device_template['templateId']}"
            response = HttpMethods(self.session, url).request(
                'PUT', payload=json.dumps(device_template))
        return response
    def get_multi_attach_payload(self, template_ids):

        return_dict = {"deviceTemplateList": []}
        i = 0
        for template_id in template_ids:
            return_dict['deviceTemplateList'].append({
                "templateId": template_id,
                "device": [],
                "isEdited": True,
                "isMasterEdited": False
            })
            url = f"{self.base_url}template/device/config/attached/{template_id}"
            attach_resp = HttpMethods(self.session, url).request('GET')
            device_list = attach_resp['json']['data']
            for device in device_list:
                payload = {
                    "templateId": template_id,
                    "deviceIds": [device['uuid']],
                    "isEdited": False,
                    "isMasterEdited": False
                }
                url = f"{self.base_url}template/device/config/input"
                input_resp = HttpMethods(self.session, url).request(
                    'POST', payload=json.dumps(payload))
                return_dict['deviceTemplateList'][i]['device'].append(
                    input_resp['json']['data'][0])
            i += 1

        return return_dict
    def add_device_template(self, device_template):
        """Add a single device template to Vmanage.


        Args:
            device_template (dict): Device Template

        Returns:
            result (list): Response from Vmanage

        """
        payload = {
            'templateName': device_template['templateName'],
            'templateDescription': device_template['templateDescription'],
            'deviceType': device_template['deviceType'],
            'factoryDefault': device_template['factoryDefault'],
            'configType': device_template['configType'],
            'featureTemplateUidRange': []
        }
        if 'policyId' in device_template:
            payload['policyId'] = device_template['policyId']
        else:
            payload['policyId'] = ''
        if 'securityPolicyId' in device_template:
            payload['securityPolicyId'] = device_template['securityPolicyId']
        else:
            payload['securityPolicyId'] = ''

        #
        # File templates are much easier in that they are just a bunch of CLI
        #
        if device_template['configType'] == 'file':
            payload['templateConfiguration'] = device_template[
                'templateConfiguration']
            url = f"{self.base_url}template/device/cli"
            response = HttpMethods(self.session,
                                   url).request('POST',
                                                payload=json.dumps(payload))
        #
        # Feature based templates are just a list of templates Id that make up a devie template.  We are
        # given the name of the feature templates, but we need to translate that to the template ID
        #
        else:
            payload['generalTemplates'] = device_template['generalTemplates']
            url = f"{self.base_url}template/device/feature"
            response = HttpMethods(self.session,
                                   url).request('POST',
                                                payload=json.dumps(payload))
        return response
Esempio n. 5
0
    def waitfor_action_completion(self, action_id):
        status = 'in_progress'
        response = {}
        action_status = None
        action_activity = None
        action_config = None
        while status == "in_progress":
            url = f"{self.base_url}device/action/status/{action_id}"
            response = HttpMethods(self.session, url).request('GET')
            ParseMethods.parse_data(response)

            if 'json' in response:
                status = response['json']['summary']['status']
                if 'data' in response['json'] and response['json']['data']:
                    action_status = response['json']['data'][0]['statusId']
                    action_activity = response['json']['data'][0]['activity']
                    if 'actionConfig' in response['json']['data'][0]:
                        action_config = response['json']['data'][0][
                            'actionConfig']
                    else:
                        action_config = None
                else:
                    action_status = status
            else:
                raise Exception(msg="Unable to get action status: No response")
            time.sleep(10)

        return {
            'action_response': response['json'],
            'action_id': action_id,
            'action_status': action_status,
            'action_activity': action_activity,
            'action_config': action_config
        }
Esempio n. 6
0
 def get_vmanage_version(self):
     api = 'system/device/controllers?model=vmanage&&&&'
     url = self.base_url + api
     response = HttpMethods(self.session, url).request('GET')
     result = ParseMethods.parse_data(response)
     version = result[0]['version']
     return version
    def detach_from_template(self, uuid, device_ip, device_type):
        """Detach a device from a template (i.e. Put in CLI mode)

        Args:
            uuid (str): The UUID of the device to detach
            device_ip (str): The System IP of the system to detach
            device_type (str): The device type of the device to detach

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        payload = {
            "deviceType": device_type,
            "devices": [{
                "deviceId": uuid,
                "deviceIP": device_ip,
            }]
        }
        url = f"{self.base_url}template/config/device/mode/cli"
        response = HttpMethods(self.session,
                               url).request('POST',
                                            payload=json.dumps(payload))
        ParseMethods.parse_data(response)

        if 'json' in response and 'id' in response['json']:
            action_id = response.json['id']
        else:
            raise Exception(
                'Did not get action ID after attaching device to template.')
        return action_id
    def add_feature_template(self, feature_template):
        """Add a feature template to Vmanage.


        Args:
            feature_template (dict): Feature Template

        Returns:
            result (list): Response from Vmanage

        """
        payload = {
            'templateName': feature_template['templateName'],
            'templateDescription': feature_template['templateDescription'],
            'deviceType': feature_template['deviceType'],
            'templateDefinition': feature_template['templateDefinition'],
            'templateType': feature_template['templateType'],
            'templateMinVersion': feature_template['templateMinVersion'],
            'factoryDefault': feature_template['factoryDefault'],
            'configType': feature_template['configType'],
            # 'feature': feature_template['feature'],
        }
        api = "template/feature"
        url = self.base_url + api
        return HttpMethods(self.session, url).request('POST', payload=json.dumps(payload))
Esempio n. 9
0
    def get_device_inputs(self, template_id, device_ids):
        """GET vSmart device inputs from vManage.

        Args:
            templateid (str): vManage assigned template identifier.
            device_ids (list): vManage assigned device ids for vSmarts.

        Returns:
            response (dict): device inputs.

        """

        payload = {
            "templateId": template_id,
            "deviceIds": device_ids,
            "isEdited": True,
            "isMasterEdited": False
        }

        api = "template/device/config/input"
        url = self.base_url + api
        response = HttpMethods(self.session,
                               url).request('POST',
                                            payload=json.dumps(payload))
        result = ParseMethods.parse_data(response)

        for item in result:
            item['csv-templateId'] = template_id

        return result
    def get_policy_definition_list(self, definition_type='all'):
        """Get all Policy Definition Lists from vManage.

        Args:
            definition_type (string): The type of Definition List to retreive

        Returns:
            response (dict): A list of all definition lists currently
                in vManage.

        """

        if definition_type == 'all':
            all_definitions_list = []
            for def_type in self.definition_types:
                definition_list = self.get_policy_definition_list(def_type)
                if definition_list:
                    all_definitions_list.extend(definition_list)
            return all_definitions_list

        definition_list = []

        if definition_type == "advancedMalwareProtection":
            url = f"{self.base_url}template/policy/definition/{definition_type}"
        else:
            url = f"{self.base_url}template/policy/definition/{definition_type.lower()}"
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        for definition in result:
            definition_detail = self.get_policy_definition(
                definition_type, definition['definitionId'])
            if definition_detail:
                definition_list.append(definition_detail)
        return definition_list
    def get_policy_list_list(self, policy_list_type='all', cache=True):
        """Get a list of policy lists

        Args:
            policy_list_type (str): Policy list type (default: all)
            cache (bool): Use cached data

        Returns:
            result (dict): All data associated with a response.

        """
        if cache and policy_list_type in self.policy_list_cache:
            response = self.policy_list_cache[policy_list_type.lower()]
        else:
            if policy_list_type == 'all':
                url = f"{self.base_url}template/policy/list"
                # result = self.request('/template/policy/list', status_codes=[200])
            else:
                url = f"{self.base_url}template/policy/list/{policy_list_type.lower()}"
                # result = self.request('/template/policy/list/{0}'.format(type.lower()), status_codes=[200, 404])

            response = HttpMethods(self.session, url).request('GET')

        self.policy_list_cache[policy_list_type.lower()] = response
        return response['json']['data']
Esempio n. 12
0
    def reattach_multi_device_templates(self, template_ids):
        """Re-Attach a template to the devices it it attached to.

        Args:
            template_id (str): The template ID to attach to
            config_type (str): Type of template i.e. device or CLI template
            is_edited (bool): True if the template has been edited
            is_master_edited (bool): For CLI device template needs to match is_edited.
                    For device templates using feature templates needs to be set to False.

        Returns:
            action_id (str): Returns the action id of the attachment

        """

        payload = self.get_multi_attach_payload(template_ids)

        if payload['deviceTemplateList'][0]['device']:
            url = f"{self.base_url}template/device/config/attachfeature"

            utils = Utilities(self.session, self.host, self.port)
            response = HttpMethods(self.session,
                                   url).request('POST',
                                                payload=json.dumps(payload))
            action_id = ParseMethods.parse_id(response)
            utils.waitfor_action_completion(action_id)
        else:
            raise RuntimeError(
                f"Could not retrieve input for template {template_ids}")
        return action_id
Esempio n. 13
0
    def detach_from_template(self, uuid, device_ip, device_type):
        """Detach a device from a template (i.e. Put in CLI mode)

        Args:
            uuid (str): The UUID of the device to detach
            device_ip (str): The System IP of the system to detach
            device_type (str): The device type of the device to detach

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        payload = {
            "deviceType": device_type,
            "devices": [{
                "deviceId": uuid,
                "deviceIP": device_ip,
            }]
        }
        url = f"{self.base_url}template/config/device/mode/cli"
        response = HttpMethods(self.session,
                               url).request('POST',
                                            payload=json.dumps(payload))
        ParseMethods.parse_status(response)
        action_id = ParseMethods.parse_id(response)

        return action_id
Esempio n. 14
0
    def get_policy_definition(self, definition_type, definition_id):
        """Get a Policy Definition from vManage.

        Args:
            definition_type (str): The defintion type of the requested policy definition
            definition_id (str): The defintion ID of the requested policy definition

        Returns:
            result (dict): All data associated with a response.

        """

        api = 'template/policy/definition/{0}/{1}'.format(
            definition_type.lower(), definition_id)
        url = self.base_url + api
        response = HttpMethods(self.session, url).request('GET')

        policy_definition = response["json"]
        if 'definition' in policy_definition:
            self.convert_list_id_to_name(policy_definition['definition'])
        if 'sequences' in policy_definition:
            self.convert_list_id_to_name(policy_definition['sequences'])
        if 'rules' in policy_definition:
            self.convert_list_id_to_name(policy_definition['rules'])
        return policy_definition
Esempio n. 15
0
    def get_policy_list_list(self, policy_list_type='all', cache=True):
        """Get a list of policy lists

        Args:
            policy_list_type (str): Policy list type
            cache (bool): Whether to cache the response

        Returns:
            result (dict): All data associated with a response.

        """
        if cache and policy_list_type in self.policy_list_cache:
            response = self.policy_list_cache[policy_list_type]
        else:
            if policy_list_type == 'all':
                api = f"template/policy/list"
                # result = self.request('/template/policy/list', status_codes=[200])
            else:
                api = f"template/policy/list/{policy_list_type.lower()}"
                # result = self.request('/template/policy/list/{0}'.format(type.lower()), status_codes=[200, 404])

            url = self.base_url + api
            response = HttpMethods(self.session, url).request('GET')

        if response['status_code'] == 404:
            return []

        self.policy_list_cache[policy_list_type] = response
        return response['json']['data']
    def update_device_template(self, device_template):
        """Update a single device template to Vmanage.


        Args:
            device_template (dict): Device Template

        Returns:
            result (list): Response from Vmanage

        """
        #
        # File templates are much easier in that they are just a bunch of CLI
        #
        # I'm not sure where this api call was found, but I can't find it in any doc and it doesn't currently work
        # if device_template['configType'] == 'file':
        #     url = f"{self.base_url}template/device/cli/{device_template['templateId']}"
        #     response = HttpMethods(self.session, url).request('PUT', payload=json.dumps(device_template))
        #     ParseMethods.parse_data(response)
        #
        # Feature based templates are just a list of templates Id that make up a device template.  We are
        # given the name of the feature templates, but we need to translate that to the template ID
        #
        #else:
        url = f"{self.base_url}template/device/{device_template['templateId']}"
        response = HttpMethods(self.session, url).request(
            'PUT', payload=json.dumps(device_template))
        return ParseMethods.parse_data(response)
Esempio n. 17
0
    def get_central_policy_list(self):
        """Get all Central Policies from vManage.

        Returns:
            response (dict): A list of all policy lists currently
                in vManage.

        """

        api = "template/policy/vsmart"
        url = self.base_url + api
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)

        central_policy_list = result
        # We need to convert the policy definitions from JSON
        for policy in central_policy_list:
            try:
                json_policy = json.loads(policy['policyDefinition'])
                policy['policyDefinition'] = json_policy
            except Exception:  # TODO: figuring out better exception type to catch
                pass
            self.policy_definitions.convert_definition_id_to_name(
                policy['policyDefinition'])
        return central_policy_list
Esempio n. 18
0
    def reattach_device_template(self, template_id):
        """Re-Attach a template to the devices it it attached to.

        Args:
            template_id (str): The template ID to attach to

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        device_list = self.get_template_attachments(template_id, key='uuid')

        template_input = self.get_template_input(template_id, device_list)

        # Then we feed that to the attach
        if 'data' in template_input and template_input['data']:
            payload = {
                "deviceTemplateList": [{
                    "templateId": template_id,
                    "device": response.json['data'],
                    "isEdited": "true",
                    "isMasterEdited": "false"
                }]
            }
            url = f"{self.base_url}template/device/config/attachfeature"
            response = HttpMethods(self.session, url).request('POST', payload=json.dumps(payload))
            if 'json' in response and 'id' in response['json']:
                action_id = response['json']['id']
                self.waitfor_action_completion(action_id)
            else:
                raise Exception(f"Did not get action ID after attaching device to template {template_id}.")
        else:
            raise Exception(f"Could not retrieve input for template {template_id}")
        return action_id
Esempio n. 19
0
    def get_policy_definition_list(self, definition_type='all'):
        """Get all Policy Definition Lists from vManage.

        Args:
            definition_type (string): The type of Definition List to retreive

        Returns:
            response (dict): A list of all definition lists currently
                in vManage.

        """

        if definition_type == 'all':
            # Get a list of hub-and-spoke because it tells us the other definition types
            # known by this server (hopefully) in the header section
            all_definitions_list = []
            definition_list_types = []
            api = "template/policy/definition/hubandspoke"
            url = self.base_url + api
            response = HttpMethods(self.session, url).request('GET')

            try:
                definition_type_titles = response['json']['header']['columns'][
                    1]['keyvalue']
            except:
                raise Exception('Could not retrieve definition types')
            for def_type in definition_type_titles:
                definition_list_types.append(def_type['key'].lower())
            for def_type in definition_list_types:
                definition_list = self.get_policy_definition_list(def_type)
                if definition_list:
                    all_definitions_list.extend(definition_list)
            return all_definitions_list

        definition_list = []

        url = f"{self.base_url}template/policy/definition/{definition_type.lower()}"
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        for definition in result:
            definition_detail = self.get_policy_definition(
                definition_type, definition['definitionId'])
            if definition_detail:
                definition_list.append(definition_detail)
        return definition_list
Esempio n. 20
0
    def attach_to_template(self, template_id, uuid, system_ip, host_name,
                           site_id, variables):
        """Attach and device to a template

        Args:
            template_id (str): The template ID to attach to
            uuid (str): The UUID of the device to attach
            system_ip (str): The System IP of the system to attach
            host_name (str): The host-name of the device to attach
            variables (dict): The variables needed by the template

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        # Construct the variable payload
        device_template_variables = {
            "csv-status": "complete",
            "csv-deviceId": uuid,
            "csv-deviceIP": system_ip,
            "csv-host-name": host_name,
            '//system/host-name': host_name,
            '//system/system-ip': system_ip,
            '//system/site-id': site_id,
        }
        # Make sure they passed in the required variables and map
        # variable name -> property mapping
        template_variables = self.get_template_input(template_id)
        for entry in template_variables['columns']:
            if entry['variable']:
                if entry['variable'] in variables:
                    device_template_variables[entry['property']] = variables[
                        entry['variable']]
                else:
                    raise Exception(
                        f"{entry['variable']} is missing for template {host_name}"
                    )

        payload = {
            "deviceTemplateList": [{
                "templateId": template_id,
                "device": [device_template_variables],
                "isEdited": False,
                "isMasterEdited": False
            }]
        }
        url = f"{self.base_url}template/device/config/attachfeature"
        response = HttpMethods(self.session,
                               url).request('POST',
                                            payload=json.dumps(payload))
        if 'json' in response and 'id' in response['json']:
            action_id = response['json']['id']
        else:
            raise Exception(
                'Did not get action ID after attaching device to template.')

        return action_id
    def get_template_input(self, template_id, device_id_list=None):
        """Get the input associated with a device attachment.

        Args:
            template_id (string): Template ID
            device_id_list (list): list of device UUID's to get input for

        Returns:
            result (dict): All data associated with a response.

        """

        if device_id_list:
            deviceIds = device_id_list
        else:
            deviceIds = []
        payload = {
            "deviceIds": deviceIds,
            "isEdited": False,
            "isMasterEdited": False,
            "templateId": template_id
        }
        return_dict = {"columns": [], "data": []}

        url = f"{self.base_url}template/device/config/input"
        response = HttpMethods(self.session,
                               url).request('POST',
                                            payload=json.dumps(payload))

        if 'json' in response:
            if 'header' in response['json'] and 'columns' in response['json'][
                    'header']:
                column_list = response['json']['header']['columns']

                regex = re.compile(r'\((?P<variable>[^(]+)\)')

                for column in column_list:
                    if column['editable']:
                        match = regex.search(column['title'])
                        if match:
                            variable = match.groups('variable')[0]
                        else:
                            # If the variable is not found, use toolTip as variable name
                            variable = column.get("toolTip")

                        entry = {
                            'title': column['title'],
                            'property': column['property'],
                            'variable': variable
                        }
                        return_dict['columns'].append(entry)
            if 'data' in response['json'] and response['json']['data']:
                return_dict['data'] = response['json']['data']

        return return_dict
Esempio n. 22
0
 def _get_device_type(self, system_ip):
     device_model = self.get_device_system_info(
         system_ip)[0]['device-model']
     url = f"{self.base_url}device/models"
     response = HttpMethods(self.session, url).request('GET')
     result = ParseMethods.parse_data(response)
     device_type = [
         device['deviceClass'] for device in result
         if device_model in device['name']
     ][0]
     return device_type
Esempio n. 23
0
    def add_central_policy(self, policy):
        """Delete a Central Policy from vManage.

        Args:
            policy: The Central Policy

        Returns:
            result (dict): All data associated with a response.

        """
        url = f"{self.base_url}template/policy/vsmart"
        HttpMethods(self.session, url).request('POST', payload=json.dumps(policy))
Esempio n. 24
0
    def get_local_policy(self):
        """Obtain a list of all configured local policies

        Returns:
            result (dict): All data associated with a response.

        """

        url = f"{self.base_url}template/policy/vedge"
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        return result
    def get_device_running_config(self, uuid):
        """
        Get the running configuration of a specific device.

        Args:
            uuid (str): UUID of device
        Returns:
            result (str): The running configuration of the specified device.
        """
        url = f"{self.base_url}template/config/running/{uuid}"
        response = HttpMethods(self.session, url).request('GET')
        return ParseMethods.parse_config(response)
Esempio n. 26
0
    def get_active_count(self):
        """Provides number of active tasks on vManage.

        Returns:
            result (dict): All data associated with a response.
        """

        api = "device/action/status/tasks/activeCount"
        url = self.base_url + api
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        return result
    def add_security_policy(self, policy):
        """Add a Security Policy from vManage.

        Args:
            policy: The Security Policy

        Returns:
            result (dict): All data associated with a response.

        """
        url = f"{self.base_url}template/policy/security"
        HttpMethods(self.session, url).request('POST', payload=json.dumps(policy))
    def get_device_templates(self):
        """Obtain a list of all configured device templates.

        Returns:
            result (dict): All data associated with a response.

        """

        api = "template/device"
        url = self.base_url + api
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        return result
Esempio n. 29
0
    def get_vmanage_ca_type(self):
        """Get vManage CA type

        Args:

        Returns:
            certificateSigning (str): The CA type.
        """

        url = f"{self.base_url}certificate"
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        return result[0]['certificateSigning']
    def get_security_policy(self):
        """Obtain a list of all configured security policies

        Returns:
            result (dict): All data associated with a response.

        """

        api = "template/policy/security"
        url = self.base_url + api
        response = HttpMethods(self.session, url).request('GET')
        result = ParseMethods.parse_data(response)
        return result