def interface(ctx, ip, vpn, name): """ Reset interface """ vmanage_device = Device(ctx.auth, ctx.host, ctx.port) vmanage_device.post_reset_interface(ip, vpn, name)
def advertised(ctx, device, json): """ Show OMP peer information """ vmanage_device = Device(ctx.auth, ctx.host) mn = MonitorNetwork(ctx.auth, ctx.host) # Check to see if we were passed in a device IP address or a device name try: ip = ipaddress.ip_address(device) system_ip = ip except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] else: system_ip = None if not json: click.echo("VPN PREFIX PROTOCOL ") click.echo("-------------------------------------") # try: omp_peers = mn.get_omp_routes_advertised(system_ip) if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(omp_peers) else: for peer in omp_peers: if 'protocol' in peer: protocol = peer['protocol'] else: protocol = '' click.echo( f"{peer['vpn-id']:<6} {peer['prefix']:<18} {protocol:<10}")
def run_module(): # define available arguments/parameters a user can pass to the module argument_spec = vmanage_argument_spec() # seed the result dict in the object # we primarily care about changed and state # change is if this module effectively modified the target # state will include any data that you want your module to pass back # for consumption, for example, in a subsequent task result = dict(changed=False, original_message='', message='') # the AnsibleModule object will be our abstraction working with Ansible # this includes instantiation, a couple of common attr would be the # args/params passed to the execution, as well as if the module # supports check mode module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) vmanage = Vmanage(module) vmanage_device = Device(vmanage.auth, vmanage.host) vmanage.result['vedges'] = vmanage_device.get_device_config_list('vedges') vmanage.result['controllers'] = vmanage_device.get_device_config_list( 'controllers') vmanage.exit_json(**vmanage.result)
def __init__(self, session, host, port=443): """Initialize Files object with session parameters. Args: session (obj): Requests Session object host (str): hostname or IP address of vManage port (int): default HTTPS 443 """ self.session = session self.host = host self.port = port self.base_url = f'https://{self.host}:{self.port}/dataservice/' self.device_templates = DeviceTemplates(self.session, self.host, self.port) self.feature_templates = FeatureTemplates(self.session, self.host, self.port) self.template_data = TemplateData(self.session, self.host, self.port) self.policy_data = PolicyData(self.session, self.host, self.port) self.policy_lists = PolicyLists(self.session, self.host, self.port) self.policy_definitions = PolicyDefinitions(self.session, self.host, self.port) self.local_policy = LocalPolicy(self.session, self.host, self.port) self.central_policy = CentralPolicy(self.session, self.host, self.port) self.vmanage_device = Device(self.session, self.host, self.port)
def received(ctx, device, json): """ Show OMP peer information """ vmanage_device = Device(ctx.auth, ctx.host, ctx.port) mn = MonitorNetwork(ctx.auth, ctx.host, ctx.port) # Check to see if we were passed in a device IP address or a device name try: ip = ipaddress.ip_address(device) system_ip = ip except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] else: system_ip = None if not json: click.echo("VPN PREFIX PROTOCOL FROM-PEER Originator COLOR STATUS") click.echo("------------------------------------------------------------------------------------------------") # try: omp_peers = mn.get_omp_routes_received(system_ip) if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(omp_peers) else: for peer in omp_peers: click.echo( f"{peer['vpn-id']:<6} {peer['prefix']:<18} {peer['protocol']:<10} {peer['from-peer']:<15} {peer['originator']:<15} {peer['color']:<15} {peer['attribute-type']:<16}" )
def table(ctx, device, json): """ Show Interfaces """ vmanage_device = Device(ctx.auth, ctx.host) # Check to see if we were passed in a device IP address or a device name try: ip = ipaddress.ip_address(device) system_ip = ip except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] else: system_ip = None if not json: click.echo( "VPNID PREFIX NEXT HOP PROTOCOL ") click.echo( "----------------------------------------------------------------") routes = vmanage_device.get_device_data('ip/routetable', system_ip) for rte in routes: if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(rte) else: if 'nexthop-addr' not in rte: rte['nexthop-addr'] = '' click.echo( f"{rte['vpn-id']:5} {rte['prefix']:<20} {rte['nexthop-addr']:<20} {rte['protocol']:8}" )
def peers(ctx, device, json): """ Show OMP peer information """ vmanage_device = Device(ctx.auth, ctx.host) mn = MonitorNetwork(ctx.auth, ctx.host) # Check to see if we were passed in a device IP address or a device name try: ip = ipaddress.ip_address(device) system_ip = ip except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] else: system_ip = None if not json: click.echo(" DOMAIN OVERLAY SITE") click.echo("PEER TYPE ID ID ID STATE UPTIME R/I/S") click.echo("---------------------------------------------------------------------------------------") # try: omp_peers = mn.get_omp_peers(system_ip) if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(omp_peers) else: for peer in omp_peers: click.echo( f"{peer['peer']:<16} {peer['type']:<7} {peer['domain-id']:<6} {'X':<7} {peer['site-id']:<6} {peer['state']:<8} {peer['up-time']:<16} X/X/X" )
def display_devices(): auth, vmanage_host = login_vmanage() vmanage_device = Device(auth, vmanage_host) device_config_list = vmanage_device.get_device_config_list('all') for device in device_config_list: try: print(device['host-name']) except KeyError: pass
def export_attachments_to_file(self, export_file, name_list=None, device_type=None): device_templates = DeviceTemplates(self.session, self.host, self.port) vmanage_device = Device(self.session, self.host, self.port) if name_list is None: name_list = [] device_template_dict = device_templates.get_device_template_dict() attachments_list = [] # Create a device config of the right type of things device_list = [] if device_type in (None, 'controllers'): device_list = vmanage_device.get_device_config_list('controllers') if device_type in (None, 'vedges'): edge_list = vmanage_device.get_device_config_list('vedges') device_list = device_list + edge_list for device_config in device_list: if 'configStatusMessage' in device_config and device_config['configStatusMessage'] != 'In Sync': continue if 'template' in device_config: if device_config['template'] in device_template_dict: template_id = device_template_dict[device_config['template']]['templateId'] else: raise Exception(f"Could not find ID for template {device_config['template']}") if name_list == [] or device_config['host-name'] in name_list: variable_dict = {} template_input = device_templates.get_template_input(template_id, device_id_list=[device_config['uuid']]) data = template_input['data'][0] for column in template_input['columns']: variable_dict[column['variable']] = data[column['property']] entry = { 'host_name': device_config['host-name'], 'device_type': device_config['deviceType'], 'uuid': device_config['chasisNumber'], 'system_ip': device_config['deviceIP'], 'site_id': device_config['site-id'], 'template': device_config['template'], 'variables': variable_dict } attachments_list.append(entry) attachment_export = {'vmanage_attachments': attachments_list} if export_file.endswith('.json'): with open(export_file, 'w') as outfile: json.dump(attachment_export, outfile, indent=4, sort_keys=False) elif export_file.endswith(('.yaml', 'yml')): with open(export_file, 'w') as outfile: yaml.dump(attachment_export, outfile, indent=4, sort_keys=False) else: raise Exception("File format not supported") return (len(attachments_list))
def device(ctx, device): """ Decommission device """ vmanage_device = Device(ctx.auth, ctx.host, ctx.port) status = vmanage_device.get_device_status(device, key='host-name') if 'uuid' in status: vmanage_device.put_device_decommission(status['uuid']) else: click.secho(f'Cannot find UUID for device {device}', fg="red")
def connections(ctx, device, json): """ Show control connections """ vmanage_device = Device(ctx.auth, ctx.host, ctx.port) mn = MonitorNetwork(ctx.auth, ctx.host, ctx.port) if device: # Check to see if we were passed in a device IP address or a device name try: ipaddress.ip_address(device) system_ip = device except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] device_list = [system_ip] else: control_device_dict = vmanage_device.get_device_config_dict( device_type='controllers', key_name='deviceIP') device_list = list(control_device_dict.keys()) if not json: click.echo( "LOCAL PEER PEER PEER SITE DOMAIN PEER PEER " ) click.echo( "SYSTEM IP TYPE PROT SYSTEM IP ID ID PRIVATE IP PUBLIC IP LOCAL COLOR PROXY STATE UPTIME" ) click.echo( "-------------------------------------------------------------------------------------------------------------------" ) for dev in device_list: try: control_connections = mn.get_control_connections(dev) if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(control_connections) else: for connection in control_connections: click.echo( f"{dev:15} {connection['peer-type']:7} {connection['protocol']:4} {connection['system-ip']:15} {connection['site-id']:6} {connection['domain-id']:6} {connection['private-ip']:15} {connection['public-ip']:15} {connection['local-color']:15} {connection['state']:11} {connection['uptime']:11}" ) # TODO: figure out correct exception type to catch except Exception: pass
def status(ctx, dev, device_type, json): #pylint: disable=unused-argument """ Show device status information """ vmanage_device = Device(ctx.auth, ctx.host) # output = mn.get_control_connections_history(sysip) # vmanage_session = ctx.obj pp = pprint.PrettyPrinter(indent=2) if dev: # Check to see if we were passed in a device IP address or a device name try: system_ip = ipaddress.ip_address(dev) device_dict = vmanage_device.get_device_status(system_ip) except ValueError: device_dict = vmanage_device.get_device_status(dev, key='host-name') if device_dict: pp.pprint(device_dict) else: click.secho(f"Could not find device {dev}", err=True, fg='red') else: device_list = vmanage_device.get_device_status_list() if json: pp.pprint(device_list) else: click.echo( f"{'Hostname':20} {'System IP':15} {'Model':15} {'Site':6} {'Status':9} {'BFD':>3} {'OMP':>3} {'CON':>3} {'Version':8} {'UUID':40} {'Serial'}" ) for device_entry in device_list: if 'bfdSessionsUp' in device_entry: bfd = device_entry['bfdSessionsUp'] else: bfd = '' if 'ompPeers' in device_entry: omp = device_entry['ompPeers'] else: omp = '' if 'controlConnections' in device_entry: control = device_entry['controlConnections'] else: control = '' click.echo( f"{device_entry['host-name']:20} {device_entry['system-ip']:15} {device_entry['device-model']:15} {device_entry['site-id']:6} {device_entry['reachability']:9} {bfd:>3} {omp:>3} {control:>3} {device_entry['version']:8} {device_entry['uuid']:40} {device_entry['board-serial']}" )
def get_free_bootstrap_device(self, dv_type="vedges"): dv = Device(self.vm_auth, self.vm_mgmt_ip) self.__logger.debug(f"Get Devices list '{dv_type}'") result = dv.get_device_list(dv_type) free_lic = dict() free_lic['vedge-cloud'] = list() free_lic['vedge-CSR-1000v'] = list() for dv in result: if dv['vedgeCertificateState'] == 'bootstrapconfiggenerated' or dv[ 'vedgeCertificateState'] == 'tokengenerated': self.__logger.debug( f'bootstrapconfiggenerated: {dv["uuid"]} {dv["serialNumber"]}' ) lic = dict() lic["uuid"] = dv["uuid"] lic["serialNumber"] = dv["serialNumber"] lic["free"] = True free_lic[dv['deviceModel']].append(lic) return free_lic
def list_interface(ctx, device, json): """ Show Interfaces """ vmanage_device = Device(ctx.auth, ctx.host) if device: # Check to see if we were passed in a device IP address or a device name try: ipaddress.ip_address(device) system_ip = device except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] device_list = [system_ip] if not json: click.echo( "IFNAME VPNID IP ADDR MAC ADDR OPER STATE DESC" ) click.echo( "----------------------------------------------------------------------------------------------------------------------" ) for dev in device_list: interfaces = vmanage_device.get_device_data('interface', dev) for iface in interfaces: if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(iface) else: if 'hwaddr' not in iface: iface['hwaddr'] = '' if 'desc' not in iface: iface['desc'] = '' if 'ip-address' not in iface: iface['ip-address'] = '' click.echo( f"{iface['ifname']:17} {iface['vpn-id']:6} {iface['ip-address']:16} {iface['hwaddr']:25} {iface['if-oper-status']:17} {iface['desc']:17}" )
def connections_history(ctx, device, json): """ Show control connections history """ vmanage_device = Device(ctx.auth, ctx.host, ctx.port) mn = MonitorNetwork(ctx.auth, ctx.host, ctx.port) # Check to see if we were passed in a device IP address or a device name try: ipaddress.ip_address(device) system_ip = device except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] if not json: click.echo( "PEER PEER PEER SITE DOMAIN PEER PRIVATE PEER PUBLIC LOCAL REMOTE" ) click.echo( "TYPE PROTOCOL SYSTEM IP ID ID PRIVATE IP PORT PUBLIC IP PORT LOCAL COLOR STATE ERROR ERROR" ) click.echo( "-------------------------------------------------------------------------------------------------------------------------------------------" ) try: control_connections_history = mn.get_control_connections_history( system_ip) if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(control_connections_history) else: for connection in control_connections_history: click.echo( f"{connection['peer-type']:8} {connection['protocol']:8} {connection['system-ip']:16} {connection['site-id']:5} {connection['domain-id']:6} {connection['private-ip']:15} {connection['private-port']:8} {connection['private-ip']:15} {connection['private-port']:7} {connection['local-color']:15} {connection['state']:11} {connection['local_enum']:7} {connection['local_enum-desc']}" ) except Exception: pass
def import_attachment_list(self, attachment_list, check_mode=False, update=False): """Import a list of device attachments to vManage. Args: attachment_list (list): List of attachments check_mode (bool): Only check to see if changes would be made update (bool): Update the template if it exists Returns: result (list): Returns the diffs of the updates. """ attachment_updates = {} attachment_failures = {} action_id_list = [] device_template_dict = self.device_templates.get_device_template_dict() vmanage_device = Device(self.session, self.host, self.port) for attachment in attachment_list: if attachment['template'] in device_template_dict: if attachment['device_type'] == 'vedge': # The UUID is fixes from the serial file/upload device_uuid = attachment['uuid'] else: # If this is not a vedge, we need to get the UUID from the vmanage since # it is generated by that vmanage device_status = vmanage_device.get_device_status( attachment['host_name'], key='host-name') if device_status: device_uuid = device_status['uuid'] else: raise Exception( f"Cannot find UUID for {attachment['host_name']}") template_id = device_template_dict[ attachment['template']]['templateId'] attached_uuid_list = self.device_templates.get_attachments( template_id, key='uuid') if device_uuid in attached_uuid_list: # The device is already attached to the template. We need to see if any of # the input changed, so we make an API call to get the input on last attach existing_template_input = self.device_templates.get_template_input( device_template_dict[attachment['template']] ['templateId'], [device_uuid]) current_variables = existing_template_input['data'][0] changed = False for property_name in attachment['variables']: # Check to see if any of the passed in varibles have changed from what is # already on the attachment. We are are not checking to see if the # correct variables are here. That will be done on attachment. if ((property_name in current_variables) and (str(attachment['variables'][property_name]) != str(current_variables[property_name]))): changed = True if changed: if not check_mode and update: action_id = self.device_templates.attach_to_template( template_id, device_uuid, attachment['system_ip'], attachment['host_name'], attachment['site_id'], attachment['variables']) action_id_list.append(action_id) else: if not check_mode: action_id = self.device_templates.attach_to_template( template_id, device_uuid, attachment['system_ip'], attachment['host_name'], attachment['site_id'], attachment['variables']) action_id_list.append(action_id) else: raise Exception(f"No template named {attachment['template']}") utilities = Utilities(self.session, self.host) # Batch the waits so that the peocessing of the attachments is in parallel for action_id in action_id_list: result = utilities.waitfor_action_completion(action_id) data = result['action_response']['data'][0] if result['action_status'] == 'failure': attachment_failures.update( {data['uuid']: data['currentActivity']}) else: attachment_updates.update( {data['uuid']: data['currentActivity']}) result = { 'updates': attachment_updates, 'failures': attachment_failures } return result
def run_module(): # define available arguments/parameters a user can pass to the module argument_spec = vmanage_argument_spec() argument_spec.update( device=dict(type='str', aliases=['device', 'host-name']), gather_subset=dict(type='list', options=subset_options), ) # seed the result dict in the object # we primarily care about changed and state # change is if this module effectively modified the target # state will include any data that you want your module to pass back # for consumption, for example, in a subsequent task result = dict(changed=False, original_message='', message='') # the AnsibleModule object will be our abstraction working with Ansible # this includes instantiation, a couple of common attr would be the # args/params passed to the execution, as well as if the module # supports check mode module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) vmanage = Vmanage(module) vmanage_device = Device(vmanage.auth, vmanage.host) vmanage_monitor = MonitorNetwork(vmanage.auth, vmanage.host) if vmanage.params['device']: # If we are passed in a device, we return specific facts about that device device_facts = {} # Check to see if we were passed in a device IP address or a device name try: system_ip = ipaddress.ip_address(vmanage.params['device']) device_status = vmanage_device.get_device_status(system_ip) except ValueError: device_status = vmanage_device.get_device_status( vmanage.params['device'], key='host-name') system_ip = device_status['system-ip'] if device_status: if vmanage.params['gather_subset']: requested_subsets = vmanage.params['gather_subset'] else: requested_subsets = subset_options device_facts['status'] = device_status if 'config' in requested_subsets: device_facts['config'] = vmanage_device.get_device_config( device_status['device-type'], system_ip) if 'omp' in requested_subsets: omp_routes_received = vmanage_monitor.get_omp_routes_received( system_ip) omp_routes_advertised = vmanage_monitor.get_omp_routes_advertised( system_ip) omp_routes = { 'received': omp_routes_received, 'advertised': omp_routes_advertised, } omp = {'routes': omp_routes} device_facts['omp'] = omp if 'control' in requested_subsets: control_connections = vmanage_monitor.get_control_connections( system_ip) control_connections_history = vmanage_monitor.get_control_connections_history( system_ip) control = { 'connections': control_connections, 'connections_history': control_connections_history } device_facts['control'] = control vmanage.result['device_facts'] = device_facts else: if vmanage.params['gather_subset']: vmanage.fail_json( msg= "gather_subset argument can only be secified with device argument", **vmanage.result) # Otherwise, we return facts for all devices sorted by device type vmanage.result['vedges'] = vmanage_device.get_device_config_list( 'vedges') vmanage.result['controllers'] = vmanage_device.get_device_config_list( 'controllers') vmanage.exit_json(**vmanage.result)
from vmanage.api.authentication import Authentication from vmanage.api.device import Device import pprint import os vmanage_host = os.environ.get('VMANAGE_HOST') vmanage_username = os.environ.get('VMANAGE_USERNAME') vmanage_password = os.environ.get('VMANAGE_PASSWORD') pp = pprint.PrettyPrinter(indent=2) auth = Authentication(host=vmanage_host, user=vmanage_username, password=vmanage_password).login() vmanage_device = Device(auth, vmanage_host) device_config_list = vmanage_device.get_device_config_list('all') pp.pprint(device_config_list)
def config(ctx, dev, device_type, json): """ Show device config information """ vmanage_device = Device(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) #pylint: disable=too-many-nested-blocks if dev: # Check to see if we were passed in a device IP address or a device name try: system_ip = ipaddress.ip_address(dev) device_dict = vmanage_device.get_device_status(system_ip) except ValueError: device_dict = vmanage_device.get_device_status(dev, key='host-name') if device_dict: if device_dict['device-type'] in ['vmanage', 'vbond', 'vsmart']: device_type = 'controllers' else: device_type = 'vedges' device_config = vmanage_device.get_device_config( device_type, device_dict['system-ip']) pp.pprint(device_config) else: click.secho(f"Could not find device {dev}", err=True, fg='red') else: click.echo( f"{'Hostname':20} {'Device IP':15} {'Model':15} {'Site':6} {'State':9} {'Template':16} {'Status':7} {'Connection':10} {'Version':7}" ) if device_type in ['all', 'control']: device_list = vmanage_device.get_device_config_list('controllers') if json: pp.pprint(device_list) else: for device_entry in device_list: if 'template' in device_entry: template = device_entry['template'] else: template = '' device_name = device_entry[ 'host-name'] if 'host-name' in device_entry else 'Unknown' reachability = device_entry[ 'reachability'] if 'reachability' in device_entry else 'Unknown' site_id = device_entry[ 'site-id'] if 'site-id' in device_entry else 'Unknown' config_status_message = device_entry[ 'configStatusMessage'] if 'configStatusMessage' in device_entry else 'Unknown' vmanage_connection_state = device_entry[ 'vmanageConnectionState'] if 'vmanageConnectionState' in device_entry else 'Unknown' version = device_entry[ 'version'] if 'version' in device_entry else 'Unknown' click.echo( f"{device_name:20} {device_entry['deviceIP']:15} {device_entry['deviceModel']:15} {site_id:6} {reachability:9} {template:16} {config_status_message:7} {vmanage_connection_state:10} {version:7}" ) if type in ['all', 'edge']: device_list = vmanage_device.get_device_config_list('vedges') if json: pp.pprint(device_list) else: for device_entry in device_list: if 'host-name' in device_entry: if 'template' in device_entry: template = device_entry['template'] else: template = '' device_name = device_entry[ 'host-name'] if 'host-name' in device_entry else 'Unknown' reachability = device_entry[ 'reachability'] if 'reachability' in device_entry else 'Unknown' site_id = device_entry[ 'site-id'] if 'site-id' in device_entry else 'Unknown' config_status_message = device_entry[ 'configStatusMessage'] if 'configStatusMessage' in device_entry else 'Unknown' vmanage_connection_state = device_entry[ 'vmanageConnectionState'] if 'vmanageConnectionState' in device_entry else 'Unknown' version = device_entry[ 'version'] if 'version' in device_entry else 'Unknown' click.echo( f"{device_name:20} {device_entry['deviceIP']:15} {device_entry['deviceModel']:15} {site_id:6} {reachability:9} {template:16} {config_status_message:7} {vmanage_connection_state:10} {version:7}" )
class CleanVmanage(object): """Reset all configuratios on a vManage instance. Executes the necessary REST calls in specific order to remove configurations applied to a vManage instance. """ def __init__(self, session, host, port=443): """Initialize Reset vManage object with session parameters. Args: session (obj): Requests Session object host (str): hostname or IP address of vManage port (int): default HTTPS 443 """ self.session = session self.host = host self.port = port self.base_url = f'https://{self.host}:{self.port}/dataservice/' self.utilities = Utilities(self.session, self.host) self.central_policy = CentralPolicy(self.session, self.host) self.local_policy = LocalPolicy(self.session, self.host) self.device = Device(self.session, self.host) self.device_templates = DeviceTemplates(self.session, self.host) self.feature_templates = FeatureTemplates(self.session, self.host) self.sec_pol = SecurityPolicy(self.session, self.host) self.policy_definitions = PolicyDefinitions(self.session, self.host) self.policy_lists = PolicyLists(self.session, self.host) def active_count_delay(self): """Delay while there are active tasks. """ activeCount = 1 while activeCount != 0: time.sleep(1.0) data = self.utilities.get_active_count() activeCount = data["activeTaskCount"] def clean_vedge_attachments(self): """Clean all vedge attachments """ data = self.device.get_device_list('vedges') for device in data: if (('deviceIP' in device) and (device['configOperationMode'] == 'vmanage')): deviceId = device['uuid'] deviceIP = device['deviceIP'] deviceType = device['deviceType'] self.device.post_device_cli_mode(deviceId, deviceIP, deviceType) self.active_count_delay() def clean_controller_attachments(self): """Clean all controller attachments """ data = self.device.get_device_list('controllers') for device in data: if (('deviceIP' in device) and (device['configOperationMode'] == 'vmanage')): deviceId = device['uuid'] deviceIP = device['deviceIP'] deviceType = device['deviceType'] self.device.post_device_cli_mode(deviceId, deviceIP, deviceType) # Requires pause between controllers self.active_count_delay() self.active_count_delay() def clean_device_templates(self): """Clean all device templates """ data = self.device_templates.get_device_templates() for device in data: templateId = device['templateId'] self.device_templates.delete_device_template(templateId) self.active_count_delay() def clean_feature_templates(self): """Clean all feature templates """ data = self.feature_templates.get_feature_templates() for device in data: #pylint: disable=no-else-continue if device['factoryDefault']: continue else: templateId = device['templateId'] self.feature_templates.delete_feature_template(templateId) self.active_count_delay() def clean_central_policy(self): """Clean all central policy """ data = self.central_policy.get_central_policy() for policy in data: policy_id = policy['policyId'] if policy['isPolicyActivated']: action_id = self.central_policy.deactivate_central_policy(policy_id) if action_id: self.utilities.waitfor_action_completion(action_id) self.central_policy.delete_central_policy(policy_id) self.active_count_delay() def clean_local_policy(self): """Clean all local policy """ data = self.local_policy.get_local_policy() for policy in data: policyId = policy['policyId'] self.local_policy.delete_local_policy(policyId) self.active_count_delay() def clean_policy_definitions(self): """Clean all policy definitions """ policy_definition_list = self.policy_definitions.get_policy_definition_list() for policy_definition in policy_definition_list: self.policy_definitions.delete_policy_definition(policy_definition['type'], policy_definition['definitionId']) self.active_count_delay() def clean_policy_lists(self): """Clean all policy lists """ policy_list_list = self.policy_lists.get_policy_list_list() for policy_list in policy_list_list: if not policy_list['readOnly'] and policy_list['owner'] != 'system': self.policy_lists.delete_policy_list(policy_list['type'], policy_list['listId']) self.active_count_delay() def clean_security_policy(self): """Clean all security policy """ version = self.utilities.get_vmanage_version() if version >= '18.2.0': data = self.sec_pol.get_security_policy() for policy in data: policyId = policy['policyId'] self.sec_pol.delete_security_policy(policyId) self.active_count_delay() # # Step 11 - Delete All UTD Specific Security Policies # version = self.utilities.get_vmanage_version() # definitionList = [] # # TODO: implement a proper semver comparison, this will fail if version is 18.30.0 # if version >= '18.4.0': # definitionList = [ # 'zonebasedfw', 'urlfiltering', 'dnssecurity', 'intrusionprevention', 'advancedMalwareProtection' # ] # #pylint: disable=chained-comparison # if version < '18.4.0' and version >= '18.2.0': # definitionList = ['zonebasedfw'] # if definitionList: # for definition in definitionList: # data = self.sec_pol.get_security_definition(definition) # if data: # for policy in data: # definitionId = policy['definitionId'] # self.sec_pol.delete_security_definition(definition, definitionId) # self.active_count_delay() # # Step 12 - Delete All Lists # data = self.pol_lists.get_policy_list_all() # for policy_list in data: # owner = policy_list['owner'] # if owner != 'system': # listType = policy_list['type'].lower() # listId = policy_list['listId'] # self.pol_lists.delete_policy_list(listType, listId) def clean_all(self): """Clean everything in vManage """ # Step 1 - Deactivate Central Policy self.clean_central_policy() # Step 2 - Detach vedges from template self.clean_vedge_attachments() # Step 3 - Detach controllers from template self.clean_controller_attachments() # Step 4 - Delete All Device Templates self.clean_device_templates() # Step 5 - Delete All Feature Templates self.clean_feature_templates() # Step 6 - Delete All Centralized Policies self.clean_central_policy() # Step 7 - Delete All Policy Definitions self.clean_policy_definitions() # Step 8 - Delete All Policy Lists self.clean_policy_lists() # Step 9 - Delete All Local Policies self.clean_local_policy() # Step 10 - Delete All Security Policies self.clean_security_policy() return ('Reset Complete')
class Files(object): """Read and write data to file. """ def __init__(self, session, host, port=443): """Initialize Files object with session parameters. Args: session (obj): Requests Session object host (str): hostname or IP address of vManage port (int): default HTTPS 443 """ self.session = session self.host = host self.port = port self.base_url = f'https://{self.host}:{self.port}/dataservice/' self.device_templates = DeviceTemplates(self.session, self.host, self.port) self.feature_templates = FeatureTemplates(self.session, self.host, self.port) self.template_data = TemplateData(self.session, self.host, self.port) self.policy_data = PolicyData(self.session, self.host, self.port) self.policy_lists = PolicyLists(self.session, self.host, self.port) self.policy_definitions = PolicyDefinitions(self.session, self.host, self.port) self.local_policy = LocalPolicy(self.session, self.host, self.port) self.central_policy = CentralPolicy(self.session, self.host, self.port) self.security_policy = SecurityPolicy(self.session, self.host, self.port) self.vmanage_device = Device(self.session, self.host, self.port) def export_templates_to_file(self, export_file, name_list=None, template_type=None): """Export templates to a file. All object IDs will be translated to names. Use a '.yml' extention to export as YAML and a '.json' extension to export as JSON. Args: export_file (str): The name of the export file name_list (list): List of device templates to export template_type (str): Template type: device or template """ template_export = {} #pylint: disable=too-many-nested-blocks if template_type != 'feature': # Export the device templates and associated feature templates device_template_list = self.template_data.export_device_template_list(name_list=name_list) template_export.update({'vmanage_device_templates': device_template_list}) feature_name_list = [] if name_list: for device_template in device_template_list: if 'generalTemplates' in device_template: for general_template in device_template['generalTemplates']: if 'templateName' in general_template: feature_name_list.append(general_template['templateName']) if 'subTemplates' in general_template: for sub_template in general_template['subTemplates']: if 'templateName' in sub_template: feature_name_list.append(sub_template['templateName']) name_list = list(set(feature_name_list)) # Since device templates depend on feature templates, we always add them. feature_template_list = self.feature_templates.get_feature_template_list(name_list=name_list) template_export.update({'vmanage_feature_templates': feature_template_list}) if export_file.endswith('.json'): with open(export_file, 'w') as outfile: json.dump(template_export, outfile, indent=4, sort_keys=False) elif export_file.endswith('.yaml') or export_file.endswith('.yml'): with open(export_file, 'w') as outfile: yaml.dump(template_export, outfile, indent=4, sort_keys=False) else: raise Exception("File format not supported") #pylint: disable=unused-argument def import_templates_from_file(self, import_file, update=False, check_mode=False, name_list=None, template_type=None): """Import templates from a file. All object Names will be translated to IDs. Args: import_file (str): The name of the import file name_list (list): List of device templates to export template_type (str): Template type: device or template check_mode (bool): Try the import, but don't make changes (default: False) update (bool): Update existing templates (default: False) """ feature_template_updates = [] device_template_updates = [] imported_template_data = {} # Read in the datafile if not os.path.exists(import_file): raise Exception(f"Cannot find file {import_file}") with open(import_file) as f: if import_file.endswith('.yaml') or import_file.endswith('.yml'): imported_template_data = yaml.safe_load(f) else: imported_template_data = json.load(f) if 'vmanage_feature_templates' in imported_template_data: imported_feature_template_list = imported_template_data['vmanage_feature_templates'] else: imported_feature_template_list = [] imported_device_template_list = [] #pylint: disable=too-many-nested-blocks if template_type != 'feature': # Import the device templates and associated feature templates if 'vmanage_device_templates' in imported_template_data: imported_device_template_list = imported_template_data['vmanage_device_templates'] if name_list: feature_name_list = [] pruned_device_template_list = [] for device_template in imported_device_template_list: if device_template['templateName'] in name_list: pruned_device_template_list.append(device_template) if 'generalTemplates' in device_template: for general_template in device_template['generalTemplates']: if 'templateName' in general_template: feature_name_list.append(general_template['templateName']) if 'subTemplates' in general_template: for sub_template in general_template['subTemplates']: if 'templateName' in sub_template: feature_name_list.append(sub_template['templateName']) imported_device_template_list = pruned_device_template_list name_list = list(set(feature_name_list)) # Since device templates depend on feature templates, we always add them. if name_list: pruned_feature_template_list = [] imported_feature_template_dict = list_to_dict(imported_feature_template_list, key_name='templateName', remove_key=False) for feature_template_name in name_list: if feature_template_name in imported_feature_template_dict: pruned_feature_template_list.append(imported_feature_template_dict[feature_template_name]) # Otherwise, we hope the feature list is already there (e.g. Factory Default) imported_feature_template_list = pruned_feature_template_list # Process the feature templates feature_template_updates = self.template_data.import_feature_template_list(imported_feature_template_list, check_mode=check_mode, update=update) # Process the device templates device_template_updates = self.template_data.import_device_template_list(imported_device_template_list, check_mode=check_mode, update=update) return { 'feature_template_updates': feature_template_updates, 'device_template_updates': device_template_updates, } # # Policy # def export_policy_to_file(self, export_file): """Export policy to a file. All object IDs will be translated to names. Use a '.yml' extention to export as YAML and a '.json' extension to export as JSON. Args: export_file (str): The name of the export file """ policy_lists_list = self.policy_lists.get_policy_list_list() policy_definitions_list = self.policy_data.export_policy_definition_list() central_policies_list = self.policy_data.export_central_policy_list() local_policies_list = self.local_policy.get_local_policy_list() security_policies_list = self.policy_data.export_security_policy_list() policy_export = { 'vmanage_policy_lists': policy_lists_list, 'vmanage_policy_definitions': policy_definitions_list, 'vmanage_central_policies': central_policies_list, 'vmanage_local_policies': local_policies_list, 'vmanage_security_policies': security_policies_list } if export_file.endswith('.json'): with open(export_file, 'w') as outfile: json.dump(policy_export, outfile, indent=4, sort_keys=False) elif export_file.endswith(('.yaml', 'yml')): with open(export_file, 'w') as outfile: yaml.dump(policy_export, outfile, default_flow_style=False) else: raise Exception("File format not supported") def import_policy_from_file(self, file, update=False, check_mode=False, push=False): """Import policy from a file. All object Names will be translated to IDs. Args: import_file (str): The name of the import file check_mode (bool): Try the import, but don't make changes (default: False) update (bool): Update existing templates (default: False) push (bool): Push tempaltes to devices if changed (default: False) """ policy_list_updates = [] policy_definition_updates = [] central_policy_updates = [] local_policy_updates = [] security_policy_updates = [] # Read in the datafile if not os.path.exists(file): raise Exception('Cannot find file {0}'.format(file)) with open(file) as f: if file.endswith('.yaml') or file.endswith('.yml'): policy_data = yaml.safe_load(f) else: policy_data = json.load(f) # Separate the feature template data from the device template data if 'vmanage_policy_lists' in policy_data: policy_list_data = policy_data['vmanage_policy_lists'] else: policy_list_data = [] if 'vmanage_policy_definitions' in policy_data: policy_definition_data = policy_data['vmanage_policy_definitions'] else: policy_definition_data = [] if 'vmanage_central_policies' in policy_data: central_policy_data = policy_data['vmanage_central_policies'] else: central_policy_data = [] if 'vmanage_local_policies' in policy_data: local_policy_data = policy_data['vmanage_local_policies'] else: local_policy_data = [] if 'vmanage_security_policies' in policy_data: security_policy_data = policy_data['vmanage_security_policies'] else: security_policy_data = [] policy_list_updates = self.policy_data.import_policy_list_list(policy_list_data, check_mode=check_mode, update=update, push=push) self.policy_lists.clear_policy_list_cache() policy_definition_updates = self.policy_data.import_policy_definition_list(policy_definition_data, check_mode=check_mode, update=update, push=push) central_policy_updates = self.policy_data.import_central_policy_list(central_policy_data, check_mode=check_mode, update=update, push=push) local_policy_updates = self.policy_data.import_local_policy_list(local_policy_data, check_mode=check_mode, update=update, push=push) security_policy_updates = self.policy_data.import_security_policy_list(security_policy_data, check_mode=check_mode, update=update, push=push) return { 'policy_list_updates': policy_list_updates, 'policy_definition_updates': policy_definition_updates, 'central_policy_updates': central_policy_updates, 'local_policy_updates': local_policy_updates, 'security_policy_updates': security_policy_updates } def export_attachments_to_file(self, export_file, name_list=None, device_type=None): """Export attachments to a file. All object IDs will be translated to names. Use a '.yml' extention to export as YAML and a '.json' extension to export as JSON. Args: export_file (str): The name of the export file """ if name_list is None: name_list = [] device_template_dict = self.device_templates.get_device_template_dict() attachments_list = [] # Create a device config of the right type of things device_list = [] if device_type in (None, 'controllers'): device_list = self.vmanage_device.get_device_config_list('controllers') if device_type in (None, 'vedges'): edge_list = self.vmanage_device.get_device_config_list('vedges') device_list = device_list + edge_list for device_config in device_list: if 'configStatusMessage' in device_config and device_config['configStatusMessage'] != 'In Sync': continue if 'template' in device_config: if device_config['template'] in device_template_dict: template_id = device_template_dict[device_config['template']]['templateId'] else: raise Exception(f"Could not find ID for template {device_config['template']}") if name_list == [] or device_config.get('host-name') in name_list: variable_dict = {} template_input = self.device_templates.get_template_input(template_id, device_id_list=[device_config['uuid']]) data = template_input['data'][0] for column in template_input['columns']: variable_dict[column['variable']] = data[column['property']] entry = { 'host_name': device_config.get('host-name'), 'device_type': device_config['deviceType'], 'uuid': device_config['chasisNumber'], 'system_ip': device_config['deviceIP'], 'site_id': device_config.get('site-id'), 'template': device_config['template'], 'variables': variable_dict } attachments_list.append(entry) attachment_export = {'vmanage_attachments': attachments_list} if export_file.endswith('.json'): with open(export_file, 'w') as outfile: json.dump(attachment_export, outfile, indent=4, sort_keys=False) elif export_file.endswith(('.yaml', 'yml')): with open(export_file, 'w') as outfile: yaml.dump(attachment_export, outfile, indent=4, sort_keys=False) else: raise Exception("File format not supported") return (len(attachments_list)) def import_attachments_from_file(self, import_file, update=False, check_mode=False, name_list=None, template_type=None): """Import policy from a file. All object Names will be translated to IDs. Args: import_file (str): The name of the import file check_mode (bool): Try the import, but don't make changes (default: False) update (bool): Update existing templates (default: False) """ template_data = {} # Read in the datafile if not os.path.exists(import_file): raise Exception(f"Cannot find file {import_file}") with open(import_file) as f: if import_file.endswith('.yaml') or import_file.endswith('.yml'): template_data = yaml.safe_load(f) else: template_data = json.load(f) if 'vmanage_attachments' in template_data: imported_attachment_list = template_data['vmanage_attachments'] else: imported_attachment_list = [] # Process the device templates result = self.template_data.import_attachment_list(imported_attachment_list, check_mode=check_mode, update=update) return result
#!/usr/bin/env python from vmanage.api.authentication import Authentication from vmanage.api.device import Device import pprint username = '******' password = '******' host = 'XX.XX.XX.XX' auth = Authentication(host=host, user=username, password=password).login() vmanage_device = Device(auth, host) device_status_list = vmanage_device.get_device_status_list() pp = pprint.PrettyPrinter(indent=2) pp.pprint(device_status_list)