def main() : parse = CiscoConfParse("cisco_ipsec.txt") # Find all crypto map entries and print parent and child print ("The crypto maps in the parsed config are : \n" ) crypto_objs = parse.find_objects(r"^crypto map CRYPTO") for obj in crypto_objs : print (obj.text) child_obj = (obj.re_search_children(r".*")) for obj2 in child_obj : print (obj2.text) print ("\n") # Find crypto maps with pfs group2 pfsg2 = parse.find_parents_w_child("crypto map CRYPTO", "set pfs group2" ) print ("The following crypto maps have pfs set to group 2: \n") for obj in pfsg2 : print (obj) # Find crypto maps without AES encryptions print ("\n") trans_set = parse.find_parents_wo_child("^crypto map CRYPTO", "set transform-set AES-SHA") print ("The crypto maps that do not have AES-SHA transform set are : \n") for obj in trans_set : print (obj)
def cisco_conf_task_3(): print "\n\nCisco parse exersise 3.\n" cfg_file = CiscoConfParse("cisco_ipsec.txt") c_maps = cfg_file.find_parents_wo_child("^crypto map CRYPTO","^ set transform-set AES") x = 1 for element in c_maps: print "entry # %s that are not using AES: %s" % (x, element) x += 1
def index(request): # net_connect = ConnectHandler(device_type='cisco_ios', ip='ip_address', username='******', password='******') # net_connect.find_prompt() # output = net_connect.send_command("show run") # tidak bisa tes koneksi langsung karena ssh cisco tidak bisa di open "connection refused" # contoh config langsung parse = CiscoConfParse("media/contoh.txt") #open file di folder media # contoh output parse interfaces active_intfs = parse.find_parents_wo_child("^interf", "shutdown") jso = json.dumps([dict(interfaces=inter) for inter in active_intfs]) with open('media/output.json', 'w') as f: f.write(json.dumps( jso, indent=4)) #membuat nama file di folder media namanya output.json return render(request, "index.html", {"parse": active_intfs, "json": jso})
class IOSDevice: """ Represents an IOS Device. Some helper functions here to assist with common stuff :type hostname: str """ def __init__(self, config_filename): self.parsed_switch_config = CiscoConfParse(config_filename) self.hostname = self._getHostname() self.interfaces = self._getNetworkInterfaces() self.router_id = self._getRouterId() def __repr__(self): return "<IOSDevice: %s>" % self.hostname def _getHostname(self): if not self.parsed_switch_config.find_lines('^hostname'): raise RuntimeError('This device has no hostname. This library requires this device has a hostname') return self.parsed_switch_config.find_lines('^hostname')[0].split()[1] def _getRouterId(self): router_id = None router_ids = self.parsed_switch_config.find_lines('router-id') if len(router_ids) > 0: router_id = self.parsed_switch_config.find_lines('router-id')[0].split()[-1] #Assume all mgmt addresses are the same elif len(self.parsed_switch_config.find_lines('^logging source-interface')) > 0: #Little hack. We don't have a router-id so lets use the logging source-id as the switch identifier for interface in self.getNetworkInterfaces(): if interface.name == self.parsed_switch_config.find_lines('^logging source-interface')[0].split()[-1]: return interface.address else: #There is no explicit mgmt address. # The router-id is set by the highest IP Address of a manually created loopback address highestAddress = IPv4Address(u'0.0.0.0') for interface in self.getNetworkInterfaces(): if "loopback" in interface.name.lower(): address = IPv4Address(unicode(interface.address)) if address > highestAddress: highestAddress = address router_id = interface.address # If there is no configured loopback the router id will be the highest IP address of the fist active (on-boot) # physical interface if router_id is None: for interface in self.getNetworkInterfaces(): address = IPv4Address(unicode(interface.address)) if address > highestAddress: highestAddress = address router_id = interface.address return router_id def _getNetworkInterfaces(self): """ Used to generate a list of NetworkInterface for a given config file :type parsed_switch_config: ciscoconfparse.CiscoConfParse :return list of interfaces """ to_return = [] switch_interfaces = self.parsed_switch_config.find_parents_wo_child("^interface", 'shutdown') for interface in switch_interfaces: #Gets the child config for this interface interface_config = CiscoConfParse(self.parsed_switch_config.find_children(interface, exactmatch=True)) #We are only interested in the interface name, not the entire interface command definition interface_name = interface.split()[1] #VRF is in global by default vrf = None description = None if interface_config.find_lines('description'): description = " ".join(interface_config.find_lines('description')[0].strip().split()[1:]) if interface_config.find_lines('^ ip vrf forwarding'): vrf = interface_config.find_lines('^ ip vrf forwarding')[0].strip().split()[-1] elif interface_config.find_lines('^ vrf forwarding'): vrf = interface_config.find_lines('^ vrf forwarding')[0].strip().split()[-1] #We only really care about this interface if it has an IP address on it #interfaces that have no addresses should be skipped if interface_config.find_lines('no ip address'): continue if interface_config.find_lines('^ ip address'): #Create a new network interface object interface = NetworkInterface(self) #In case we want to skip this interface and not show it for some reason should_add_address = True for address in interface_config.find_lines('^ ip address'): #We can have multiple addresses here, have to allow for secondaries if "secondary" in address: secondary_address = SecondaryAddress(interface) secondary_address.address = address.strip().split('ip address')[1].split()[0] secondary_address.netmask = address.strip().split('ip address')[1].split()[1] interface.secondary.append(secondary_address) else: if "no" in address or "negotiated" in address: should_add_address = False break if len(interface_config.find_lines('channel-group')) > 0: should_add_address = False break interface.address = address.strip().split('ip address')[1].split()[0] interface.name = interface_name interface.netmask = address.strip().split('ip address')[1].split()[1] interface.vrf = vrf interface.description = description to_return.append(interface) return to_return def getNetworkInterfaces(self): """ Used to generate a list of NetworkInterface for a given config file :type parsed_switch_config: ciscoconfparse.CiscoConfParse :return list of interfaces """ if self.interfaces is None: self.interfaces = self._getNetworkInterfaces() return self.interfaces def getHostname(self): """ Returns the hostname on this device :rtype: str """ return self.hostname def getParsedSwitchConfig(self): """ Returns a parsed switch config object (CiscoConfParse) for this device :rtype: CiscoConfParse """ return self.parsed_switch_config()
#!/usr/bin/python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse('conf.txt') basic_search = parse.find_parents_wo_child('^interface', 'desc') print basic_search #Save output to text file f = open('output.txt', 'w') print >> f, basic_search f.close() #Sanitize the output to replace , with a new line f = open('output.txt','r') filedata = f.read() f.close() newdata = filedata.replace(", ","\n") f = open('output.txt','w') f.write(newdata) f.close() #Sanitize he output for ' f = open('output.txt','r') filedata = f.read() f.close() newdata = filedata.replace("'","") f = open('output.txt','w') f.write(newdata) f.close()
# Suppose we need to find a list of all interfaces that have CDP evabled; this # implies a couple of things: # 1. CDP has not been disabled globally with [no cdp run] # 2. The interfaces in question are not configured with [no cdp enable] from ciscoconfparse import CiscoConfParse parse = CiscoConfParse('bucksnort.conf') if not bool(parse.find_objects(r'no cdp run')): cdp_intfs = parse.find_parents_wo_child(r'^interface', r'no cdp enable') print cdp_intfs
#!/usr/bin/env python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("../configs/sample_01.ios") # Return a list of all ATM interfaces and subinterfaces atm_intfs = parse.find_lines("^interface\sATM") # Return a list of all interfaces with a certain QOS policy qos_intfs = parse.find_parents_w_child("^interf", "service-policy") # Return a list of all active interfaces (i.e. not shutdown) active_intfs = parse.find_parents_wo_child("^interf", "shutdown")
def testValues_find_parents_wo_child(self): ## test find_parents_wo_child for config, args, result_correct in self.find_parents_wo_child_Values: cfg = CiscoConfParse(config) test_result = cfg.find_parents_wo_child(**args) self.assertEqual(result_correct, test_result)
#!/usr/bin/env python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("../configs/sample_01.ios") # Return a list of all ATM interfaces and subinterfaces atm_intfs = parse.find_lines("^interface\sATM") # Return a list of all interfaces with a certain QOS policy qos_intfs = parse.find_parents_w_child( "^interf", "service-policy" ) # Return a list of all active interfaces (i.e. not shutdown) active_intfs = parse.find_parents_wo_child( "^interf", "shutdown" )