本文整理汇总了Python中ciscoconfparse.CiscoConfParse.find_lines方法的典型用法代码示例。如果您正苦于以下问题:Python CiscoConfParse.find_lines方法的具体用法?Python CiscoConfParse.find_lines怎么用?Python CiscoConfParse.find_lines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ciscoconfparse.CiscoConfParse
的用法示例。
在下文中一共展示了CiscoConfParse.find_lines方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: standardizeInt
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def standardizeInt(parsed_config):
interfaces = parsed_config.find_lines('^interface.+?thernet')
for i in interfaces:
famobj = CiscoConfParse(parsed_config.find_children(i, exactmatch=True))
if (famobj.find_lines('switchport mode access')):
if (not famobj.find_lines('spanning-tree portfast')):
cfgDiffs.append(i)
cfgDiffs.append(" spanning-tree portfast")
示例2: conf_to_xml
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [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_negative_ignore_ws
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def testValues_negative_ignore_ws(self):
## test find_lines WITHOUT ignore_ws
result_correct = []
cfg = CiscoConfParse(self.c03)
test_result = cfg.find_lines(
'set snmp community read-only myreadonlystring',
)
self.assertEqual(result_correct, test_result)
示例4: testValues_ignore_ws
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def testValues_ignore_ws(self):
## test find_lines with ignore_ws flag
result_correct = self.c03
cfg = CiscoConfParse(self.c03)
test_result = cfg.find_lines(
'set snmp community read-only myreadonlystring',
ignore_ws = True
)
self.assertEqual(result_correct, test_result)
示例5: testValues_negative_ignore_ws
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def testValues_negative_ignore_ws():
"""test find_lines WITHOUT ignore_ws"""
config = ['set snmp community read-only myreadonlystring']
result_correct = list()
cfg = CiscoConfParse(config)
test_result = cfg.find_lines(
'set snmp community read-only myreadonlystring',
ignore_ws = False
)
assert result_correct==test_result
示例6: testValues_ignore_ws
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def testValues_ignore_ws():
## test find_lines with ignore_ws flag
config = ['set snmp community read-only myreadonlystring']
result_correct = config
cfg = CiscoConfParse(config)
test_result = cfg.find_lines(
'set snmp community read-only myreadonlystring',
ignore_ws = True
)
assert result_correct==test_result
示例7: __init__
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
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]
#.........这里部分代码省略.........
示例8: _getNetworkInterfaces
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
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
示例9: testValues_find_lines
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def testValues_find_lines(self):
for config, args, result_correct in self.find_lines_Values:
cfg = CiscoConfParse(config)
test_result = cfg.find_lines(**args)
self.assertEqual(result_correct, test_result)
示例10: str
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
from ciscoconfparse import CiscoConfParse
import sys
#Accepts input using command line arguments
dname = str(sys.argv[1])
parse = CiscoConfParse(dname)
print '---------start----------'
print dname
print '-------------------'
print 'Global Config Audit'
print '-------------------'
#Requirement - Enabled
#vtp mode
if parse.find_lines('^vtp\smode\stransparent') or parse.find_lines('^vtp\smode\soff'):
print 'vtp mode = PASS'
else:
print 'vtp mode = FAIL'
#service password-encryption
if parse.find_lines('^service\spassword-encryption'):
print 'service password-encryption = PASS'
else:
print 'service password-encryption = FAIL'
#ip source-route
if parse.find_lines('^no\sip\ssource-route'):
print 'no ip source-route = PASS'
else:
print 'no ip source-route = FAIL'
示例11: CiscoConfParse
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
#!/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" )
示例12: standardize_configs
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
def standardize_configs(ip, chan):
print "Downloading running configuration"
output = send_command("enable", "!Tmgmt", "skip", "sh run", read=True, chan=chan)
# Captures running config
capture = re.findall(r"!\r\nver.*end", output, re.S).pop()
# Parses running config
print "Parsing configuraion"
output = CiscoConfParse(capture.splitlines())
# Corrects DNS Setting
dns = output.find_lines(r"ip dns server-address.*")
output.replace_lines(r"ip dns server-address.*", r"ip dns server-address 10.210.1.214 10.220.1.200")
print ("Correcting dns entry")
send_command(
"no {0}".format(dns.pop()), "ip dns server-address 10.210.1.214 10.220.1.200", configure=True, chan=chan
)
# Enables IGMP Snooping globally
output.insert_after(r"hostname", r"ip multicast active")
print ('Enabling "ip multicast"')
send_command("ip multicast active", configure=True, chan=chan)
# print 'Searching for interfaces with dhcp helper'
# virtual_interfaces = output.find_objects_w_child(r'interface ve.*', r'\s+ip\s+helper.*',)
# for intf in virtual_interfaces:
# interface = intf.text
# print interface
# has_dhcp_helper = intf.has_child_with(r'ip helper.*')
# for line in intf.all_children:
# if 'ip address' in line.text:
# address = line.text
# print address
# if 'helper-address' in line.text:
# dhcp = line.text
# print dhcp
# if has_dhcp_helper:
# writer.writerow((ip, interface, address, dhcp))
#
# Iterates through interfaces and cleans up misconfigurations
for interface in output.find_objects(r"^interface.+"):
has_loop_detection = interface.has_child_with(r"loop-detection")
has_bpdu_guard = interface.has_child_with(r"stp-bpdu-guard")
has_root_protection = interface.has_child_with(r"spanning-tree\sroot-protect")
has_no_flow_control = interface.has_child_with(r"no\sflow-control")
is_layer3_intf = (interface.has_child_with(r"ip\s+add")) or ("interface ve.*" in interface.text)
# Temporarily disabled
# Remove loop-detection misconfiguration
if has_loop_detection and has_bpdu_guard:
interface.delete_children_matching("loop-detection")
print ('Removing "loop-detection" from {0}'.format(interface.text))
send_command(interface.text, "no loop-detection", configure=True)
# Remove spanning-tree root-protect misconfiguration
if has_root_protection:
interface.delete_children_matching(r"spanning-tree\sroot-protect")
print ('Removing "spanning-tree root-protect" from {0}'.format(interface.text))
send_command(interface.text, "no spanning-tree root", configure=True)
# Adds IGMP snooping and QoS to Layer 3 interfaces
if is_layer3_intf and not ("loopback" in interface.text or "management" in interface.text):
interface.append_to_family(r" trust dscp")
print ('Adding "trust dscp" to {0}'.format(interface.text))
send_command(interface.text, "trust dscp", configure=True, chan=chan)
interface.append_to_family(r" ip igmp version 2")
print ('Adding "ip igmp version 2" to {0}'.format(interface.text))
send_command(interface.text, "ip igmp version 2", configure=True, chan=chan)
# enables flow-control
if has_no_flow_control:
interface.delete_children_matching(r"no\sflow-control.+")
print ('Enabling "flow-control" on {0}'.format(interface.text))
send_command(interface.text, "flow-control", configure=True, chan=chan)
return output
示例13: print
# 需要导入模块: from ciscoconfparse import CiscoConfParse [as 别名]
# 或者: from ciscoconfparse.CiscoConfParse import find_lines [as 别名]
# vrf_objs = parse.find_objects('^vrf context DMZ')
# for obj in vrf_objs:
# print (obj.ioscfg)
# static_raw = obj.re_match_iter_typed(STATIC_RE)
# print(static_raw)
DMZ_static_list = parse.find_children_w_parents('^vrf context DMZ',STATIC_RE)
for x in DMZ_static_list:
static_rawlist = x.split()
static_net = static_rawlist[2]
static_dst = static_rawlist[3]
#static_net = IPNetwork(static_raw)
static_routes.append(str(static_net)+' '+str(static_dst))
DMZ_prefix_list = parse.find_lines('^ip prefix-list DMZ_STATIC.*permit.*')
for y in DMZ_prefix_list:
prefixlist_rawlist = y.split()
prefixlist_entry = prefixlist_rawlist[6]
prefixlist_entries.append(prefixlist_entry)
print("Directly Connected Interface Networks in VRF DMZ")
print '\n'.join(directly_connected)
print("Static routes under VRF DMZ")
print '\n'.join(static_routes)
print("Prefix list networks permitted under DMZ_STATIC")
print '\n'.join(prefixlist_entries)
#static_raw = static_rawlist[2]
#print(static_raw)