本文整理汇总了Python中ciscoconfparse.CiscoConfParse.find_all_children方法的典型用法代码示例。如果您正苦于以下问题:Python CiscoConfParse.find_all_children方法的具体用法?Python CiscoConfParse.find_all_children怎么用?Python CiscoConfParse.find_all_children使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ciscoconfparse.CiscoConfParse
的用法示例。
在下文中一共展示了CiscoConfParse.find_all_children方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_int
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
def get_int(switch, interface):
""" Get a config snippet from a device """
conf_file = conf_dir + switch + extension
interface = expand_port(interface)
try:
parse = CiscoConfParse(conf_file)
except:
print("Error: could not load config for ", conf_file)
sys.exit(1)
search_int = "^interface " + interface + "$"
if args.match:
m = parse.find_objects_w_child(parentspec=search_int,
childspec=args.match)
if m:
print(args.switch + ',' + args.int + ',' + args.match)
else:
iface = parse.find_all_children(search_int)
if iface:
print('!' + switch + ' ' + interface)
for line in iface:
print(line)
if iface:
print('!')
示例2: conf_to_xml
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
def conf_to_xml(f):
ccp = CiscoConfParse(f)
print ccp
hostname = ccp.find_lines("^hostname")[0].lower()
hostname = re.sub("hostname ", "", hostname)
xmlroot = etree.Element('add')
doc = etree.Element('doc')
xmlroot.append(doc)
f_id = etree.Element('field')
f_id.attrib["name"] = "id"
f_id.text = hostname
doc.append(f_id)
f_type = etree.Element('field')
f_type.attrib["name"] = "doctype"
f_type.text = "full config"
doc.append(f_type)
f_content = etree.Element('field')
f_content.attrib["name"] = "content"
f_content.text = "\n".join(ccp.find_lines(".*"))
doc.append(f_content)
types = ['interface', 'router', 'ip vrf', 'ip access-list', 'class-map', 'policy-map']
for t in types:
for obj in ccp.find_objects(r"^"+t):
subdoc = etree.Element('doc')
subid = hostname + " " + obj.text
subf_id = etree.Element('field')
subf_id.attrib["name"] = "id"
subf_id.text = subid
subdoc.append(subf_id)
subf_type = etree.Element('field')
subf_type.attrib["name"] = "doctype"
subf_type.text = t
subdoc.append(subf_type)
subf_content = etree.Element('field')
subf_content.attrib["name"] = "content"
subf_content.text = "\n".join(ccp.find_all_children("^" + obj.text))
subdoc.append(subf_content)
doc.append(subdoc)
xmlstring = etree.tostring(xmlroot, pretty_print=True)
etree.ElementTree(xmlroot).write(xmldir + "/" + hostname + ".xml")
示例3: testValues_find_all_chidren02
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
def testValues_find_all_chidren02():
"""Ensure we don't need a comment at the end of a """
""" parent / child block to identify the end of the family"""
CONFIG = ['thing1',
' foo',
' bar',
' 100',
' 200',
' 300',
' 400',
'thing2',]
RESULT_CORRECT = ['thing1',
' foo',
' bar',
' 100',
' 200',
' 300',
' 400',]
cfg = CiscoConfParse(CONFIG)
test_result = cfg.find_all_children('^thing1')
assert RESULT_CORRECT==test_result
示例4: netcompare
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
def netcompare(origin, target, no_command):
origin_file = CiscoConfParse(origin, syntax='ios', factory=False)
target_file = CiscoConfParse(target, syntax='ios', factory=False)
diff_add_no_commands = []
for line in origin_file.objs:
if line.parent.linenum == line.linenum and line.is_config_line is True:
parent_match = target_file.find_objects(
'^'+re.escape(line.text)+'$',
exactmatch=True, ignore_ws=False)
if len(parent_match) == 0 and not re.match(
no_command + "\s.*", line.text):
diff_add_no_commands.append(no_command + ' ' + line.text)
elif len(parent_match) == 0 and re.match(
no_command + "\s.*", line.text):
line_text_without_no = re.match(
no_command + "\s(.*)", line.text)
diff_add_no_commands.append(line_text_without_no.group(1))
if len(line.children) > 0 and len(parent_match) != 0:
result_comparison = compare_children_prefix_no(
line, target_file, no_command)
if len(result_comparison) > 0:
diff_add_no_commands.append(result_comparison)
diff_add_commands = []
for line in target_file.objs:
if line.parent.linenum == line.linenum and line.is_config_line is True:
parent_match = origin_file.find_objects(
'^'+re.escape(line.text)+'$',
exactmatch=True, ignore_ws=False)
if len(parent_match) == 0:
parent_with_children = target_file.find_all_children(
'^'+re.escape(line.text)+'$')
for line_in_parent_with_children in parent_with_children:
diff_add_commands.append(line_in_parent_with_children)
if len(line.children) > 0 and len(parent_match) != 0:
result_comparison = compare_children(line, origin_file)
if len(result_comparison) > 0:
diff_add_commands.append(
compare_children(line, origin_file))
return merge_commands(diff_add_no_commands, diff_add_commands)
示例5: CiscoConfParse
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
# Push the "output" thru CiscoConfParse
# http://www.pennington.net/py/ciscoconfparse/
parse = CiscoConfParse(output)
obj_list = []
obj_list = parse.find_objects(r'hostname')
if obj_list:
hostname = obj_list[0].re_match(r'hostname\s(\S+)$')
print ("Grabbed config from: " + hostname)
else:
f_run.write(switch + ",Config grab failed \n")
continue
router_bgp = parse.find_all_children(r'router\sbgp\s\d+$')
if router_bgp:
bgp_as_grab = re.search(r"router\sbgp\s(\d+)", router_bgp[0])
bgp_as = bgp_as_grab.group(1)
for line in router_bgp:
network_line = bgp_reg_ex.search(line)
if network_line:
f_run.write(switch + "," + hostname + "," + bgp_as + "," + network_line.group(1) + "," + network_line.group(2) + "," + str(iptools.ipv4.ip2long(network_line.group(1))) + "," + str(iptools.ipv4.netmask2prefix(network_line.group(2))) + "\n")
else:
f_run.write(switch + "," + "No BGP found?")
#f_run.write(kdkdkdkdk)
f_run.close()
示例6: variable
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
#!/usr/bin/env pytho
'''
This script parses cisco.txt file and searches for 'crypto map CRYPTO' lines using CCP module.
Then it displays childrens indented multiple times for each element of crypto_map variable (list).
'''
import pprint
from ciscoconfparse import CiscoConfParse
fo = open('cisco.txt', 'r') # Opening text file as FileObject with open() function
parse = CiscoConfParse(fo) # Loading the file to CCF module as argument for parsing later
crypto_map = parse.find_all_children(r'^crypto map CRYPTO')
# In the line above using find_all_children method with regex (parsing)
print 'Show the content of crypto_map variable: \n',crypto_map
print
print 'Show me parent-child relationships for crypto map CRYPTO lines in cisco.txt file: '
# Iterate over elements of crypto_map list and display in a nice human readable format
for line in crypto_map:
# pprint.pprint(line) # Replaced with the below as suggested by Kirk (clean output)
print(line.strip("\n"))
示例7: open
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
f = open ('sunspeed_pre_move.csv', 'r')
csv_f = csv.reader(f)
next(csv_f, None)
#output/scratch file with all output data #
sfile = open('new_config_output.txt', 'wa')
for row in csv_f:
servername = row[2]
serverinterface = row[4]
configfilename = row[35]
slotinformation = row[36]
interfaceinformation = row[37]
ethinfo = str("interface GigabitEthernet"+slotinformation+"/"+interfaceinformation)
parse= CiscoConfParse("/home/jp/Documents/Migration_tools/SUNSPEED/CONFIGS/"+configfilename+".inf.uk.cliffordchance.com-Running.config")
portconfig = parse.find_all_children(ethinfo)
print (servername+"-"+serverinterface)
sfile.write("new name is "+servername+"-"+serverinterface +", ")
# portconfig is a list of all port information found in the config file matched to the interface #
for line in portconfig:
if "description" in line:
desc = line
print desc
sfile.write("old name is "+desc+", ")
if "switchport access" in line:
vlanid = str(line)
print str(vlanid)
sfile.write(vlanid +", ")
if "speed" in line:
speed = line
print speed
示例8: len
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
SERVICEPOLICY_RE = re.compile(r'service-policy\soutput\s(\S+)')
INTERFACE_RE = re.compile(r'^interface\s(\S+)')
CLASS_MAP_RE = re.compile(r'^class-map\smatch-any\s(\S+)')
# Loop through the interfaces, looking for service-policy output.
for intobj in interfaces:
# if the interface has an output service-policy jump in
if intobj.re_search_children("service-policy output"):
# Find the class-map children of the policy-map - line terminated to stop half matches
class_maps_t = parse.find_children("policy-map " + intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str) + "$")
# CiscoConfParse helpfully includes the parent config, which we don't need so we remove it.
class_maps_t.remove ("policy-map " + intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str))
# If there's only on class-map, it's a parent policy in a hirearchical shaper
if len(class_maps_t) == 1:
policy_map_parent = intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str)
# Find all the children of the parent policy
policy_map_c = parse.find_all_children("policy-map " + intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str))
# Step through them looking for the child policy-map name
for pmap_p_child in policy_map_c:
pmap_p_child_policy = re.search(r"service-policy (\S+)", pmap_p_child)
if pmap_p_child_policy:
# We've found it - set the child policy name
child_policy = pmap_p_child_policy.group(1)
class_maps_t = []
# Get the class maps for the policy-map
class_maps_t = parse.find_children(r"policy-map " + pmap_p_child_policy.group(1) + "$")
# Remove the parent policy-map config - it's not useful to us
class_maps_t.remove ("policy-map " + pmap_p_child_policy.group(1))
else:
# We've found more than one class-map so this must be parent policy directly on the interface
policy_map_parent = "No Parent"
# Set the policy name
示例9: file
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
#!/usr/bin/env python
"""Stefano Pirrello Week 1 Excercise 8 - 11"""
from ciscoconfparse import CiscoConfParse
#Exercise 8
#The script should find all of the crypto map entries in
#the file (lines that begin with 'crypto map CRYPTO') and for each crypto map entry print out its children.
config_obj = CiscoConfParse("cisco_ipsec.txt")
cmaps = config_obj.find_all_children(r"crypto map CRYPTO")
# print type(cmaps)
# print len(cmaps)
print "\n\nExercise 8:"
for cmap in cmaps:
print cmap
#Exercies 9
#Find all of the crypto map entries that are using PFS group2
config_obj = CiscoConfParse("cisco_ipsec.txt")
cmaps = config_obj.find_objects(r"crypto map CRYPTO")
print "\n\nExercise 9:"
#cmaps = config_obj.find_all_children(r"crypto map CRYPTO")
cmaps_list = []
for cmap in cmaps:
if cmap.re_search_children(r"set\spfs\sgroup2"):
cmaps_list.append(cmap)
示例10: testValues_find_all_children
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
def testValues_find_all_children(self):
## test find_all_chidren
for config, args, result_correct in self.find_all_children_Values:
cfg = CiscoConfParse(config)
test_result = cfg.find_all_children(**args)
self.assertEqual(result_correct, test_result)
示例11: CiscoConfParse
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
#!/usr/bin/python
# Getting familiar with ciscoconfparse
# get_ipints.py
__author__ = 'Claudia'
import sys
#raw_input("Press Return to continue...")
from ciscoconfparse import CiscoConfParse
config = CiscoConfParse(str(sys.argv[1]),factory=True)
vl = config.find_all_children("^vlan")
lvl=len(vl)
for v in vl:
print v
print ("Number of items in list: %s" % lvl)
print ("Vlans from config file: %s" % str(sys.argv[1]))
raw_input("Press Return to continue to Router/SVI Section...")
int = config.find_objects_w_child(parentspec=r"^interface",childspec=r"ip address")
lint = len(int)
for i in int:
print i
print ("Number of items in list: %s" % lint)
print ("Routed Interfaces from config file: %s" % str(sys.argv[1]))
示例12: CiscoConfParse
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
#!/usr/bin/python
# get_vlans.py
__author__ = 'Claudia'
import sys
#raw_input("Press Return to continue...")
from ciscoconfparse import CiscoConfParse
config = CiscoConfParse(str(sys.argv[1]))
vl = config.find_all_children("^vlan")
lvl=len(vl)
for v in vl:
print v
print ("Number of items in list: %s" % lvl)
print ("Vlans from config file: %s" % str(sys.argv[1]))
raw_input("Press Return to continue to IP Section...")
ipint = config.find_objects_w_child(parentspec=r"^interface",childspec=r"ip address")
lipint = len(ipint)
for i in ipint:
print i
print ("Number of items in list: %s" % lipint)
print ("IPs from config file: %s" % str(sys.argv[1]))
示例13: MainFunc
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
def MainFunc(filelist,filepath,protocol,linstr,outputfolder,label_list):
mydict,mylist=returnAttributes(protocol,label_list)
print("-----------------------1")
print(mydict)
print("-----------------------2")
print(mylist)
mylist3=mylist[:]
for k,v in mydict.items():
if '/' in v:
vv=v.split('/')
for e in vv:
if len(e)>0:
mylist3.append(e)
#filelist=os.listdir(filepath)
for eachfile in filelist:
if '.DS' in eachfile:
continue
with open(ProjectPath+"/"+outputfolder+"/input_"+linstr,"w")as fout:
pass
for eachfile in filelist:
if '.DS' in eachfile:
continue
with open(filepath+'/'+eachfile)as fin:
linsout=[]
for eachline in fin:
if "Authentication Data Removed" in eachline or '/*' in eachline:
#print(eachline)
pass
else:
linsout.append(eachline)
with open(filepath+'/'+eachfile,"w")as fout:
fout.writelines(linsout)
if len(eachfile)>0:
print(eachfile)
protocol2=r'[ \t]*'+protocol+'.*$'
linstr2=r'[\s]*'+linstr+'[\s]*$'
parse_file = CiscoConfParse(str(filepath+'/'+eachfile))
#val_block0=parse_file.find_blocks(protocol2,exactmatch=False,ignore_ws=True)
val_children0=parse_file.find_all_children(protocol2,exactmatch=False,ignore_ws=True)
val0=val_children0
#print("val_children000000")
#print(val_children0)
if str(linstr)!="input patterns":
parse0 = CiscoConfParse(val0)
val_block=parse0.find_blocks(linstr2,exactmatch=False,ignore_ws=True)
#val_children=parse_file.find_children_w_parents(parentstr,linstr,ignore_ws=True)
val_children=parse0.find_all_children(linstr2,exactmatch=False,ignore_ws=True)
print("val_block...")
print(val_block)
print('val_children...')
print(val_children)
val1=val_block+val_children
else:
val1=val_children0
#val1=val_children
#print("val1///")
#print(val1)
parse1 = CiscoConfParse(val1)
val2=[]
for each in mylist:
#print("each............................."+each)
each2=r'[\s]*'+each+'[\w\s;\[\]\-\.]+.*'
temp=parse1.find_all_children(each2,exactmatch=True,ignore_ws=True)
val2.extend(temp)
#val=parse.find_all_children('group CONNECTOR',exactmatch=False,ignore_ws=True)
#print('val2....')
#print(val2)
val3=[]
#print("mylist3........")
#print(mylist3)
for each in val2:
itema=each.replace('{','').replace('#','').strip()+','
if islistcontainstr(mylist3,each) and not itema in val3:
#print("+++++++++++++++++++++++++++++++++++++++++++++++++++++"+each)
val3.append(itema)
Output=[]
outputtab=0
for tab in range(len(mylist)):
Output.append([])
for k,v in mydict.items():
matchlist=[]
if v=="int":
pattern=re.compile(r"[\s]*"+k+"[\s]*[\d]+")
for each in val3:
#print(each)
matchlist.extend(pattern.findall(each))
#print("222222222222222222222222222")
#print(matchlist)
#print(val3)
#.........这里部分代码省略.........
示例14: variable
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_all_children [as 别名]
#!/usr/bin/env pytho
'''
This script parses cisco.txt file and searches for 'crypto map CRYPTO' lines using CCP module.
Then it displays childrens indented multiple times for each element of crypto_map variable (list).
'''
import pprint
from ciscoconfparse import CiscoConfParse
file = open('cisco.txt', 'r') # Opening text file wiht open() function
parse = CiscoConfParse(file) # Loading the file to CCF module as argument for parsing later
crypto_map = parse.find_all_children(r'^crypto map CRYPTO') # Using find_all_children method with regex (parsing)
print 'Show the content of crypto_map variable: \n',crypto_map
print
print 'Show me parent-child relationships for crypto map CRYPTO lines in cisco.txt file: '
# Iterate over elements of crypto_map list and display in a nice human readable format
for line in crypto_map:
pprint.pprint(line)
quit()