Exemple #1
0
def node_list(args):

	element_position = 1
	argument_node = args.hostname
	template_list = []
	template_list_copy = template_list
	auditcreeper_flag = True

	### NODE_OBJECT IS A LIST OF ALL THE NODES IN THE DATABASE WITH ALL ATTRIBUTES
	node_object = process_nodes()

	### MATCH_NODE IS A LIST OF NODES THAT MATCHES THE ARGUEMENTS PASSED IN BY USER
	match_node = search_node(argument_node,node_object)

	### NODE_TEMPLATE IS A LIST OF ALL THE TEMPLATES BASED ON PLATFORMS AND DEVICE TYPE
	node_template = process_templates()
	
	### MATCH_TEMPLATE IS A LIST OF 'MATCH' AND/OR 'NO MATCH' IT WILL USE THE MATCH_NODE
	### RESULT, RUN IT AGAINST THE NODE_OBJECT AND COMPARES IT WITH NODE_TEMPLATE DATABASE
	### TO SEE IF THERE IS A TEMPLATE FOR THE SPECIFIC PLATFORM AND TYPE.
	match_template = search_template(template_list,match_node,node_template,node_object,auditcreeper_flag)
	### THIS WILL PARSE OUT THE GENERATED CONFIGS FROM THE *.JINJA2 FILE TO A LIST

	if(len(match_node) == 0):
		print("[+] [NO MATCHING NODES AGAINST DATABASE]")
		print("")

	else:
		print("[")
		template_list = template_list_copy[0]

		for index in initialize.element:

			print("    {")
			print("\t\"hostname\": \"{}\"\n" \
				  "\t\"mgmt_ip\": \"{}\"\n" \
				  "\t\"os\": \"{}\"\n" \
				  "\t\"platform\": \"{}\"\n" \
				  "\t\"type\": \"{}\"".format(node_object[index]['hostname'],node_object[index]['ip'],node_object[index]['opersys'],node_object[index]['platform'],node_object[index]['type']) + "\n" \
				  "\t\"data\": {\n" \
				  "\t    \"managed_configs\": {" \
			)
			for template in template_list:
				print ("\t\t   \"{}\"".format(template))
			print("\t     }")
			print("\t }")

			template_list = get_updated_list(template_list_copy)

#			if(len(template_list_copy) != 1):
#				template_list_copy.pop(0)
#				template_list = template_list_copy[0]

			if(element_position == len(initialize.element)):
				print("    }")
			else:
				print("    },")

			element_position = element_position + 1
		print("]")
def render(template_list, node_object, auditcreeper, output, with_remediation):

    ### TEMPLATE_LIST_COPY TAKE A COPY OF THE CURRENT TEMPLATE_LIST
    template_list_copy = template_list

    if (auditcreeper):
        template_list = template_list_copy[0]
#	print("[!] [THE FOLLOWING TEMPLATE(S) IS/ARE RENDERED:]")
    for index in initialize.element:

        print("{}".format(node_object[index]['hostname']))
        for template in template_list:
            ### THIS CALLS THE DIRECTORY MODULE WHICH WILL RETURN THE CORRECT DIRECTORY PATH BASED ON DEVICE PLATFORM, OS AND TYPE
            directory = get_template_directory(node_object[index]['platform'],
                                               node_object[index]['opersys'],
                                               node_object[index]['type'])
            env = Environment(loader=FileSystemLoader("{}".format(directory)),
                              lstrip_blocks=True,
                              trim_blocks=True)
            baseline = env.get_template(template)
            f = open(
                "/rendered-configs/{}.{}".format(
                    node_object[index]['hostname'], template.strip('jinja2')) +
                "conf", "w")
            config_list = []
            config = baseline.render(nodes=node_object[index],
                                     with_remediation=with_remediation)
            f.write(config)
            f.close
            print("{}{}".format(directory, template))
            if (output):
                print("{}".format(config))

            f = open(
                "/rendered-configs/{}.{}".format(
                    node_object[index]['hostname'], template.strip('jinja2')) +
                "conf", "r")
            init_config = f.readlines()
            ### THE BELOW PARSE_COMMANDS FUNCTION WILL ONLY GET EXECUTED IF NEEDS TO STORE COMMANDS IN THE GLOBAL VARILABLE INITIALIZE.CONFIGURATION FOR PUSH
            ### PUSH_CFGS(OUTPUT = TRUE) VS RENDER_CONFIG(OUTPUT = FALSE) FUNCTIONS.
            if (output != True):
                parse_commands(node_object[index], init_config)

        if (auditcreeper):
            template_list = get_updated_list(template_list_copy)
        print

    return None
Exemple #3
0
def policies(policy_list,node_policy,policy_list_copy,auditcreeper_flag):

	redirect = []
	commands = []

	for index in initialize.element_policy:
		redirect.append('push_acl')
		# THE BELOW FORLOOP TAKES CARE OF THE CONFIGS FOR EACH POLICY TERM PER FIREWALL NODES
		for policy in policy_list:
			###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
			print("{}".format(node_policy[index]['hostname']))
			print("{}".format(policy))
			parse_firewall_acl(node_policy[index],policy)
			if(auditcreeper_flag):
				policy_list = get_updated_list(policy_list_copy)

	return commands
def policies(policy_list, node_policy, policy_list_copy, auditcreeper_flag):

    commands = []
    redirect = []
    """
		:param redirect: A list of which method superloop will access. This variable is sent to the multithread_engine. Each element is a redirect per node.
		:type alt_key_file: list

		:param commands: Referenced to global variable commands which keeps track of all commands per node.
		:type commands: list
	"""
    for index in initialize.element_policy:
        redirect.append('push_acl')
        # THE BELOW FORLOOP TAKES CARE OF THE CONFIGS FOR EACH POLICY TERM PER FIREWALL NODES
        for policy in policy_list:
            ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
            print("{}".format(node_policy[index]['name']))
            print("{}".format(policy))
            parse_firewall_acl(node_policy[index], policy)
            if auditcreeper_flag:
                policy_list = get_updated_list(policy_list_copy)

    return commands
Exemple #5
0
def render(template_list, node_object, auditcreeper, output, with_remediation):
    global with_remediate
    with_remediate = with_remediation
    template_list_copy = template_list
    if auditcreeper:
        template_list = template_list_copy[0]
    for index in initialize.element:
        get_hardware_vendor_template_directory = get_template_directory(
            node_object[index]['hardware_vendor'],
            node_object[index]['opersys'], node_object[index]['type'])
        print("{}".format(node_object[index]['name']))
        for template in template_list:
            config = process_jinja2_template(node_object, index, template,
                                             with_remediation)
            print("{}{}".format(get_hardware_vendor_template_directory,
                                template))
            if (output):
                print("{}".format(config))
            with open(
                    '{}/rendered-configs/{}.{}'.format(
                        get_home_directory(), node_object[index]['name'],
                        template.replace('jinja2', '')) + 'conf', 'r') as file:
                init_config = f.readlines()
            """
				The below parse_commands() function will only get executed if
				it needs to store commands in the global variable initialize.configuration
				for push. push_cfgs(output = True) vs render_config(output = False) functions.
			"""
            if output != True:
                parse_commands(node_object[index],
                               init_config,
                               set_notation=False)
            print()
        if auditcreeper:
            template_list = get_updated_list(template_list_copy)

    return None
Exemple #6
0
def auditdiff_engine(template_list, node_object, auditcreeper, output,
                     remediation):

    redirect = []
    command = []
    ### RENDERED_CONFIG IS TO ACCOMODATE JUNIPER PLATFORM BY APPENDING A 'LOAD REPLACE TERMINAL' TO GET THE DIFF OUTPUT
    rendered_config = []
    rendered_config.append('load replace terminal')
    edit_list = []
    no_diff = 0

    ### PUSH_CONFIGS IS A LIST OF THE FINAL CONFIGS TO BE PUSHED
    #	push_configs = []

    ### INDEX_POSITION IS THE INDEX OF ALL THE MATCHED FILTER_CONFIG AGAINST THE BACKUP_CONFIGS. THE INDEX IS COMING FROM THE BACKUP_CONFIG
    index_position = 0

    ### NODE_INDEX KEEPS TRACK OF THE INDEX IN INITIALIZE.NTW_DEVICE. IF REMEDIATION IS NOT REQUIRED (CONFIGS MATCHES TEMPLATE), THEN THE NODE IS POPPED OFF
    ### INITIALIZE.NTW_DEVICE AND NOTHING IS CHANGED ON THAT DEVICE
    node_index = 0

    ### AUDIT_FILTER_RE IS THE REGULAR EXPRESSION TO FILTER OUT THE AUDIT FILTER IN EVERY TEMPLATE
    AUDIT_FILTER_RE = r"\[.*\]"

    ### TEMPLATE_LIST_COPY TAKE A COPY OF THE CURRENT TEMPLATE_LIST
    template_list_original = template_list[:]
    template_list_copy = template_list

    if (auditcreeper):
        template_list = template_list_copy[0]

#	print "TEMPLATE_LIST: {}".format(template_list)

### THIS SECTION OF CODE WILL GATHER ALL RENDERED CONFIGS FIRST AS IT'S REQUIRED FOR ALL PLATFORMS (CISCO & JUNIPER)
### JUNIPER DOES NOT REQUIRE BACKUP-CONFIGS IN ORDER TO BE DIFFED SO INSTEAD IT WILL JUST PUSH (PUSH_CFGS) THE TEMPLATE AND PERFORM THE DIFF ON THE DEVICE ITSELF.
### CISCO WILL REQUIRE BACKUP-CONFIGS (GET_CONFIG)
    for index in initialize.element:

        if (node_object[index]['platform'] == 'juniper'):

            ### THIS WILL RETURN A SORTED JUNIPER TEMPLATE LIST BASED ON JUNIPER'S 'SHOW CONFIGURATION' OUTPUT
            template_list = get_sorted_juniper_template_list(template_list)
#			print("TEMPLATE_LIST FIRST PHASE: {}".format(template_list))

        for template in template_list:

            ### THIS SECTION OF CODE WILL PROCESS THE TEMPLATE AND OUTPUT TO A *.CONF FILE
            directory = get_template_directory(node_object[index]['platform'],
                                               node_object[index]['opersys'],
                                               node_object[index]['type'])
            env = Environment(loader=FileSystemLoader("{}".format(directory)))
            baseline = env.get_template(template)
            f = open(
                "/rendered-configs/{}.{}".format(
                    node_object[index]['hostname'],
                    template.split('.')[0]) + ".conf", "w")

            ### GENERATING TEMPLATE BASED ON NODE OBJECT
            config = baseline.render(nodes=node_object[index])

            f.write(config)
            f.close
            if (node_object[index]['platform'] == 'cisco'):

                ### THIS SECTION OF CODE WILL OPEN THE RENDERED-CONFIG *.CONF FILE AND STORE IN RENDERED_CONFIG AS A LIST
                f = open(
                    "/rendered-configs/{}.{}".format(
                        node_object[index]['hostname'],
                        template.split('.')[0]) + ".conf", "r")
                init_config = f.readlines()
                ### RENDERED_CONFIG IS A LIST OF ALL THE CONFIGS THAT WAS RENDERED FROM THE TEMPLATES (SOURCE OF TRUTH)

            if (node_object[index]['platform'] == 'juniper'):

                ### THIS SECTION OF CODE WILL OPEN THE RENDERED-CONFIG *.CONF FILE AND STORE IN RENDERED_CONFIG AS A LIST
                f = open(
                    "/rendered-configs/{}.{}".format(
                        node_object[index]['hostname'],
                        template.split('.')[0]) + ".conf", "r")
                init_config = f.readlines()
                ### RENDERED_CONFIG IS A LIST OF ALL THE CONFIGS THAT WAS RENDERED FROM THE TEMPLATES (SOURCE OF TRUTH)

                for config_line in init_config:
                    strip_config = config_line.strip('\n')
                    ### THIS WILL REMOVE ANY LINES THAT ARE EMPTY OR HAS A '!' MARK
                    if (strip_config == '' or strip_config == "!"):
                        continue
                    else:
                        rendered_config.append(strip_config)

                ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
#				print ("RENDERED CONFIG: {}".format(rendered_config))

        template_list = get_updated_list(template_list_copy)

        if (node_object[index]['platform'] == 'cisco'):
            redirect.append('get_config')
            command.append([''])
        ### JUNIPER DEVICES WILL RECEIVE A DIFFERENT REDIRECT THAN CISCO PLATFORM
        ### THREE ADDITIONAL COMMANDS ARE APPENEDED AT THE END, ^D, SHOW | COMPARE AND ROLLBACK 0
        ### ALL TEMPLATES MATCHING ARE EXECUTED AT ONCE PER DEVICE
        elif (node_object[index]['platform'] == 'juniper'):
            redirect.append('get_diff')
            rendered_config.append('\x04')
            rendered_config.append('show | compare')
            rendered_config.append('rollback 0')
            command.append(rendered_config)

    ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
#	print"REDIRECT: {}".format(redirect)
###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
#	print"COMMAND: {}".format(command)
#	print("[+] [COMPUTING DIFF. STANDBY...]")
    multithread_engine(initialize.ntw_device, redirect, command)

    ### RESETING TEMPLATE_LIST TO ORIGINAL LIST

    ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
    #	print("ORIGINAL_LIST: {}".format(template_list_original))
    template_list = template_list_original

    ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
    #	print("TEMPLATE_LIST: {}".format(template_list))

    ### REINITIALIZING TEMPLATE_LIST TO THE ORIGINAL LIST OF TEMPLATES
    if (auditcreeper):
        template_list = template_list_original[0]

    ### THIS FOR LOOP WILL LOOP THROUGH ALL THE MATCHED ELEMENTS FROM THE USER SEARCH AND AUDIT ON SPECIFIC TEMPLATE OR IF NO ARGUMENT IS GIVEN, ALL TEMPLATES

    for index in initialize.element:

        ### NODE_CONFIG IS THE FINALIZED CONFIG TO PUSH TO THE NODE FOR REMEDIATION
        node_configs = []
        ntw_device_pop = True
        ### TEMPLATE_NAME IS SET TO TRUE IN ORDER TO PRINT OUT THE TEMPLATE HEADING WHEN RECURSING
        template_name = True

        if (not remediation):
            print("Only in the device: -")
            print("Only in the generated config: +")
            print("{}".format(node_object[index]['hostname']))

        ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
        template_list_juniper = template_list[:]
        if (node_object[index]['platform'] == 'juniper'):

            ### THIS WILL RETURN A SORTED JUNIPER TEMPLATE LIST BASED ON JUNIPER'S 'SHOW CONFIGURATION' OUTPUT
            template_list = get_sorted_juniper_template_list(template_list)

        ### THIS WILL LOOP THROUGH ALL THE TEMPLATES SPECIFIED FOR THE PARTICULAR HOST IN NODES.YAML
        for template in template_list:

            ### THIS SECTION IS FOR CISCO SYSTEMS PLATFORM ###
            if (node_object[index]['platform'] == 'cisco'):

                cisco_audit_diff(node_object, index, template, AUDIT_FILTER_RE,
                                 output, remediation)

            ### THIS SECTION IS FOR JUNIPER NETWORKS PLATFORM ###
            if (node_object[index]['platform'] == 'juniper'):

                directory = get_template_directory(
                    node_object[index]['platform'],
                    node_object[index]['opersys'], node_object[index]['type'])
                ### THIS SECTION OF CODE WILL OPEN DIFF-CONFIG *.CONF FILE AND STORE IN DIFF_CONFIG AS A LIST
                f = open(
                    "/diff-configs/{}".format(node_object[index]['hostname']) +
                    ".conf", "r")
                init_config = f.readlines()
                ### DIFF_CONFIG ARE THE DIFFERENTIAL CONFIGS GENERATED BY THE /DIFF-CONFIGS/*.CONF FILE
                diff_config = []

                for config_line in init_config:
                    strip_config = config_line.strip('\n')
                    diff_config.append(strip_config)

                ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
#				print ("DIFF CONFIG: {}".format(diff_config))

                RE = re.compile(r'\[edit\s({})'.format(template.split('.')[0]))
                search = list(filter(RE.match, diff_config))

                if (len(search) == 0):
                    print("{}{} (none)".format(directory, template))
                    print('')
                    no_diff = no_diff + 1
                    if (no_diff == len(template_list)):
                        break
                    if (len(template_list) > 1):
                        juniper_audit_diff(directory, template, template_list,
                                           diff_config, edit_list, search)
                    else:
                        continue

                else:
                    ### THIS FIRST SECTION WILL FIND ALL THE INDEXES WITH THE '[edit <TEMPLATE>]' AND APPEND IT TO THE EDIT_LIST
                    ### EDIT_LIST MAINTAINS A LIST OF ALL THE INDEXES THAT PERTAIN TO THE TEMPLATES
                    for line in diff_config:
                        if (re.search(
                                '\[edit\s{}'.format(template.split('.')[0]),
                                line)):
                            element = diff_config.index(line)
                            edit_list.append(element)
                            ###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
#							print('ELEMENT: {}'.format(element))
#							print("{}".format(line))

###UN-COMMENT THE BELOW PRINT STATEMENT FOR DEBUGING PURPOSES
#					print('EDIT_LIST 1st: {}'.format(edit_list))
#					print("index_of_template_list: {}".format(index_of_template_list))
#					print("length_template_list: {}".format(length_template_list))
                    juniper_audit_diff(directory, template, template_list,
                                       diff_config, edit_list, search)

#					print("end_of_template_list: {}".format(end_of_template_list))
### UPON THE LAST TEMPLATE, IT WILL THEN FIND THE CLOSING CURLY BRACES INDEX NUMBER TO APPEND TO THE EDIT_LIST

        if (auditcreeper):
            initialize.configuration.append(node_configs)
            if (ntw_device_pop == True):
                initialize.ntw_device.pop(node_index)
                initialize.configuration.pop(node_index)
            template_list = get_updated_list(template_list_original)

#	if(remediation):
#		print("[+]: PUSH ENABLED")
#		print("[!]: PUSH DISABLED")

    return None
Exemple #7
0
def node_list(args):
    argument_node = args.name
    auditcreeper = True
    element_position = 1
    template_list = []
    template_list_copy = template_list
    """
		:param argument_node: Argument accepted as regular expression.
		:type augument_node: str
		
		:param auditcreeper: When auditcreeper is active/non-active.
		:type auditcreeper: bool
		
		:param element_position: Keeps track of the position.
		:type element_position: int 
		
		:param template_list: Initializing list of templates
		:type template_list: list
		
		:param template_list_copy: Memory reference to template_list
		:type ext: list
		
	"""
    node_object = process_nodes()
    match_node = search_node(argument_node, node_object)
    node_template = process_templates()
    match_template = search_template(template_list, match_node, node_template,
                                     node_object, auditcreeper)
    """
		:param node_object: All node(s) in the database with all attributes.
		:type node_object: list

		:param node_template: All templates based on hardware_vendor and device type.
		:type node_template: list

		:param match_node: Nodes that matches the arguements passed in by user.
		:type match_node: list

		:param match_template: Return a list of 'match' and/or 'no match'.
		:type match_template: list 
	"""
    if len(match_node) == 0:
        print('+ No matching node(s) found in database.')
        print('')
    else:
        print('[')
        template_list = template_list_copy[0]
        for index in initialize.element:
            print('    {')
            if (args.attribute == 'protocols' or args.attribute == 'all'):
                print("\t\"bgp\": [")
                for peer in node_object[index]['bgp']:
                    print("\t   {")
                    print("\t\t\"peer\": \"{}\"\n" \
                         "\t\t\"remote_as\": \"{}\"" \
                      .format(peer['peer'],
                        peer['remote_as']
                       )
                    )
                    print("\t   },")
                    print('        ]')
            print("\t\"created_at\": \"{}\"\n" \
               "\t\"created_by\": \"{}\"" \
              .format(node_object[index]['created_at'],node_object[index]['created_by'])
              )
            print("\t\"data\": {\n" \
               "\t    \"managed_configs\": {" \
              )
            for template in template_list:
                print("\t\t   \"{}\"".format(template))
            print('\t     }')
            print('         }')
            print("\t\"domain_name\": \"{}\"\n" \
               "\t\"hardware_vendor\": \"{}\"\n" \
               "\t\"lifecycle_status\": \"{}\"\n" \
               "\t\"location_name\": \"{}\"\n" \
               "\t\"mgmt_con_ip4\": \"{}\"\n" \
               "\t\"mgmt_ip4\": \"{}\"\n" \
               "\t\"mgmt_oob_ip4\": \"{}\"\n" \
               "\t\"mgmt_snmp_community4\": \"{}\"\n" \
               "\t\"name\": \"{}\"\n" \
               "\t\"opersys\": \"{}\"" \
              .format(node_object[index]['domain_name'],
                node_object[index]['hardware_vendor'],
                node_object[index]['lifecycle_status'],
                node_object[index]['location_name'],
                node_object[index]['mgmt_con_ip4'],
                node_object[index]['mgmt_ip4'],
                node_object[index]['mgmt_oob_ip4'],
                node_object[index]['mgmt_snmp_community4'],
                node_object[index]['name'],
                node_object[index]['opersys'],
              )
            )
            if (args.attribute == 'protocols' or args.attribute == 'all'):
                print("\t\"ospf\": [")
                for peer in node_object[index]['ospf']:
                    print("\t   {")
                    print("\t\t\"neighbor_id\": \"{}\"\n" \
                         "\t\t\"area\": \"{}\"\n" \
                         "\t\t\"priority: \"{}\"\n" \
                         "\t\t\"state: \"{}\"" \
                      .format(peer['neighbor_id'],
                        peer['area'],
                        peer['priority'],
                        peer['state']
                       )
                    )
                    print("\t   },")
                    print('        ]')
            print("\t\"platform_name\": \"{}\"" \
             .format(node_object[index]['platform_name']
              )
            )
            if (args.attribute == 'ports' or args.attribute == 'all'):
                print("\t\"ports\": [")
                for interface in node_object[index]['ports']:
                    print("\t   {")
                    print("\t\t\"access_vlan\": \"{}\"\n" \
                         "\t\t\"acl4_in\": \"{}\"\n" \
                         "\t\t\"acl4_out: \"{}\"\n" \
                         "\t\t\"admin_status: \"{}\"\n" \
                         "\t\t\"created_at: \"{}\"\n" \
                         "\t\t\"created_by: \"{}\"\n" \
                         "\t\t\"data: \"{}\"\n" \
                         "\t\t\"drain_status: \"{}\"\n" \
                         "\t\t\"farend_name: \"{}\"\n" \
                         "\t\t\"if_speed: \"{}\"\n" \
                         "\t\t\"ip4: \"{}\"\n" \
                         "\t\t\"management: \"{}\"\n" \
                         "\t\t\"mtu: \"{}\"\n" \
                         "\t\t\"name: \"{}\"\n" \
                         "\t\t\"node_name: \"{}\"\n" \
                         "\t\t\"portrole_name: \"{}\"\n" \
                         "\t\t\"type: \"{}\"\n" \
                         "\t\t\"updated_at: \"{}\"\n" \
                         "\t\t\"updated_by: \"{}\"\n" \
                         "\t\t\"wan_link: \"{}\"" \
                      .format(interface['access_vlan'],
                        interface['acl4_in'],
                        interface['acl4_out'],
                        interface['admin_status'],
                        interface['created_at'],
                        interface['created_by'],
                        interface['data'],
                        interface['drain_status'],
                        interface['farend_name'],
                        interface['if_speed'],
                        interface['ip4'],
                        interface['management'],
                        interface['mtu'],
                        interface['name'],
                        interface['node_name'],
                        interface['portrole_name'],
                        interface['type'],
                        interface['updated_at'],
                        interface['updated_by'],
                        interface['wan_link']
                      )
                    )
                print("\t   },")
                print('        ]')
            print("\t\"role_name\": \"{}\"\n" \
               "\t\"serial_num\": \"{}\"\n" \
               "\t\"software_image\": \"{}\"\n" \
               "\t\"software_version\": \"{}\"\n" \
                           "\t\"status\": \"{}\"\n" \
               "\t\"type\": \"{}\"\n" \
                           "\t\"updated_at\": \"{}\"\n" \
                           "\t\"updated_by\": \"{}\"" \
              .format(node_object[index]['role_name'],
                node_object[index]['serial_num'],
                node_object[index]['software_image'],
                node_object[index]['software_version'],
                node_object[index]['status'],
                node_object[index]['type'],
                node_object[index]['updated_at'],
                node_object[index]['updated_by']
              )
            )
            template_list = get_updated_list(template_list_copy)
            if element_position == len(initialize.element):
                print('    }')
            else:
                print('    },')
            element_position = element_position + 1
        print(']')

    return None
Exemple #8
0
def mediator(template_list,node_object,auditcreeper,output,with_remediation):
	redirect = [] 
	command = [] 
	template_counter = 0
	node_index = 0 
	AUDIT_FILTER_RE = r'\[.*\]'
	template_list_original = template_list[:]
	template_list_copy = template_list
	authentication = True

	"""
	:param redirect: A list of which method superloop will access. This variable is sent to the multithread_engine. Each element is a redirect per node.
	:type alt_key_file: list
	
	:param command: A list within a list where each element represents per node of commands to execute.
	:type command: list
	
	:param template_counter: Used to keep track of the number of templates it cycles through for Juniper.
	:type template_counter: int
	
	:param node_index: Keeps track of the index in initialize.ntw_device. If remediation is not required (configs matches template), then the node is popped of       initialize.ntw_device and nothing is changed on that device.
	:type node_index: int
	
	:param AUDIT_FILTER_RE: Regular expression to filter out the audit filter in every template.
	:type AUDIT_FILTER_RE: str
	
	:param template_list_original: Take a duplicate copy of template_list
	:type template_list_original: list
	
	:param template_list_copy: Memory reference to template_list
	:type template_list_copy: list
	
	"""
	"""
	The mediator is broken up into two sections. The first section of code will gather all rendered configs first as it's required for all hardware vendors 
	(Cisco, Juniper & F5). Juniper does not require backup-configs in order to be diff'ed. The diff is server (node) side processed and the results 
	are returned back to superloop. Cisco hardware_vendors will require backup-configs (get_config) where the diffs are processed locally.
	"""
	if auditcreeper:
		template_list = template_list_copy[0]
	for index in initialize.element:
		rendered_config = []
		if node_object[index]['hardware_vendor'] == 'juniper':
			"""
                Juniper's diff output are always in a certain stanza order. 
                The template_list ordered processed may very well not be in the 
                same order as Juniper's. In order to keep it consistent, we must 
                call the function get_sorted_juniper_template() and it will 
                return a sorted Juniper's stanza list.
			"""
			template_list = get_sorted_juniper_template_list(template_list)
			rendered_config.append('load replace terminal')
		for template in template_list:
			process_jinja2_template(node_object,index,template,with_remediation)
			"""
				Compiling the rendered configs from template and preparing
				for pushing to node.
			"""
			if node_object[index]['hardware_vendor'] == 'juniper':
				template_counter = template_counter + 1
				with open('{}/rendered-configs/{}.{}'.format(get_home_directory(),node_object[index]['name'],template.split('.')[0]) + '.conf','r') as file:
					init_config = file.readlines()
				for config_line in init_config:
					strip_config = config_line.strip('\n')
					if(strip_config == '' or strip_config == "!"):
						continue	
					else:
						rendered_config.append(strip_config)	
				"""
					This below statement will check to see if it's the last 
					template for the node. It will then append 3 commands to the list.
				"""
				if template_counter == len(template_list):
					rendered_config.append('\x04')
					rendered_config.append('show | compare')
					rendered_config.append('rollback 0')
				"""
					Uncomment the below print statement for debugging purposes
				"""
					#print("RENDERED CONFIG: {}".format(rendered_config))
		"""
			The below statement will only execute if user is auditing 
			against multiple templates. If only one template is being 
			audited, do no pop off element.
		"""
		if len(template_list) != 1:
			template_list = get_updated_list(template_list_copy)
		if node_object[index]['hardware_vendor'] == 'cisco' or node_object[index]['hardware_vendor'] == 'f5':
			redirect.append('get_config')
			command.append([''])
			"""
			Juniper devices will receive a different redirect than 
			Cisco. Three additional commands are appeneded 
			at the end, ^d, show | compare and rollback 0.  All templates 
			matching are executed at once per device
		"""
		elif node_object[index]['hardware_vendor'] == 'juniper':
			redirect.append('get_diff')
			command.append(rendered_config)
			template_counter = 0
	"""
		Uncomment the below print statement for debugging purposes
	"""
	#print('REDIRECT: {}'.format(redirect))
	#print('TEMPLATE_LIST: {}'.format(template_list))
	#print('COMMAND: {}'.format(command))
	multithread_engine(initialize.ntw_device,redirect,command,authentication)
	template_list = template_list_original
	if(auditcreeper):
		template_list = template_list_original[0]
	for index in initialize.element:
		edit_list = []
		node_configs = []
		diff_config = []
		ntw_device_pop = True 
		"""
			:param edit_list: Anchor points for Juniper audits based on the edit stanza.
			:type edit_list: list

			:param node_configs: Finalized configs used to push to device
			:type node_configs: list

			:param diff_config: Differential configs generated by the ~/diff-configs/*.conf file
			:type diff_config: list

			:param ntw_device_pop: Pop off each node once audit is complete.
			:type ntw_device_pop: bool
		"""
		if not with_remediation:
			print("Only in the device: -")
			print("Only in the generated config: +")
			print ("{}".format(node_object[index]['name']))
		if node_object[index]['hardware_vendor'] == 'cisco' or node_object[index]['hardware_vendor'] == 'f5':
			generic_audit_diff(node_object,index,template,template_list,AUDIT_FILTER_RE,output,with_remediation)
		elif node_object[index]['hardware_vendor'] == 'juniper':
			template_list = get_sorted_juniper_template_list(template_list)
			directory = get_template_directory(node_object[index]['hardware_vendor'],node_object[index]['opersys'],node_object[index]['type'])
			with open('{}/diff-configs/{}'.format(get_home_directory(),node_object[index]['name']) + '.conf','r') as file:
				init_config = file.readlines()
			for config_line in init_config:
				strip_config = config_line.strip('\n')
				diff_config.append(strip_config)
			for output in diff_config:
				if 'errors' in output:
					error = True
					break
				else:
					error = False
			if error:
				print('+ Please check error(s) in template(s)')
				break
			else:
				juniper_mediator(node_object,template_list,diff_config,edit_list,index)
				juniper_audit_diff(directory,template_list,diff_config,edit_list)
		if auditcreeper:
			initialize.configuration.append(node_configs)
			if ntw_device_pop == True:
				initialize.ntw_device.pop(node_index)
				initialize.configuration.pop(node_index)
			template_list = get_updated_list(template_list_original)

	return None