【问题标题】:PyParsing Different String LengthsPyParsing不同的字符串长度
【发布时间】:2016-07-20 10:34:01
【问题描述】:

我正在为防火墙配置文件编写解析器。 总的来说,我是 PyParsing 和 Python 的新手。

问题是如果出现超过 3 个参数,我该如何解析,(xxxx,xxxx,xxxx) != (xxxx,xxxx,xxxx,xxxx),如果每行不包含任何规则,所有规则都可以正常工作并正确解析所有内容多于 3 个字符串,但我们可以看到 [Firewall [F1]] 在地址字段后包含“NAT”,无论我们如何更改规则都会被忽略。

使用 (def printTokens(s,loc,toks): #s=orig string, loc=location, toks=matched tokens)

请在使用第 4 个参数(“NAT”)以及我们删除它时查看 2 个输出。 提前致谢!需要解析所有内容,包括实施规则的“NAT”。

from pyparsing import *

#===================================GRAMMER==================================
zone = Literal("zone")    
zoneid = Word(alphanums)
host = Literal("host")
hostid = Word(alphanums)
interface = Literal("interface")
interfaceid = Word(alphanums)
firewall = Literal("firewall")
firewallid = Word(alphanums)
router = Literal("router")
routerid = Word(alphanums)

fstop = Literal(".")
comma = Suppress(",") #Converter for ignoring the results of a parsed expression.
slash = Literal("/")
ocbracket = Literal("{")
ccbracket = Literal("}")
sobracket = Literal("[")
scbracket = Literal("]")
hyphen = Literal("-")
underline = Literal("_") 
word = Word(alphas)


#===================================IP-TYPE=================================

ip=Combine(Word(nums)+            
        fstop+ Word(nums) + 
        fstop+ Word(nums) + 
        fstop + Word(nums))

subnet = Combine(slash +Word(nums))

address = ip + Optional(subnet)


#===================================RULES===================================

#adword = address + word

zoneRule = zone + zoneid + address
hostRule = host + hostid + ocbracket
interfaceRule = interface + interfaceid + address 
interfaceRule2 = interface + interfaceid + address + word
firewallRule = firewall + firewallid + ocbracket
routerRule = router + routerid + ocbracket

endRule = ccbracket


rule = zoneRule | hostRule | interfaceRule | interfaceRule2 | firewallRule | routerRule | endRule 
rules = OneOrMore(rule)

#===================================DATA=====================================
details = """zone zone1 10.1.0.0/24                   
         zone backbone 10.254.0.0/24
         zone zone 10.2.0.0/24
         host ha {
             interface iha 10.1.0.1
         }
         host hb {
            interface ihb 10.2.0.1
         }
         firewall f1 {
            interface ifla 10.1.0.254 
            interface iflback 10.254.0.101 nat
         }
         router r2 {
            interface ir2back 10.254.0.102
         }
         router r3 {
            interface ir3b 10.2.0.103
         }"""

#==================================METHODS==================================

    def printTokens(s,loc,toks):   #s=orig string, loc=location, toks=matched tokens
    print (toks)

zoneRule.setParseAction(printTokens) 
hostRule.setParseAction(printTokens)
interfaceRule.setParseAction(printTokens)
interfaceRule2.setParseAction(printTokens) #takes in 4 instances where as 3 declared
firewallRule.setParseAction(printTokens)
routerRule.setParseAction(printTokens)
endRule.setParseAction(printTokens)

rules.parseString(details)


#================================OUTPUT RESULT WITH NAT=================================
"""
['zone', 'zone1', '10.1.0.0', '/24']
['zone', 'backbone', '10.254.0.0', '/24']
['zone', 'zone', '10.2.0.0', '/24']
['host', 'ha', '{']
['interface', 'iha', '10.1.0.1']        
['}']
['host', 'hb', '{']
['interface', 'ihb', '10.2.0.1']
['}']
['firewall', 'f1', '{']
['interface', 'ifla', '10.1.0.254']
['interface', 'iflback', '10.254.0.101']"""
#================================OUTPUT RESULT WITHOUT NAT=================================
"""['zone', 'zone1', '10.1.0.0', '/24']
['zone', 'backbone', '10.254.0.0', '/24']
['zone', 'zone', '10.2.0.0', '/24']
['host', 'ha', '{']
['interface', 'iha', '10.1.0.1']
['}']
['host', 'hb', '{']
['interface', 'ihb', '10.2.0.1']
['}']
['firewall', 'f1', '{']
['interface', 'ifla', '10.1.0.254']
['interface', 'iflback', '10.254.0.101']
['}']
['router', 'r2', '{']
['interface', 'ir2back', '10.254.0.102']
['}']
['router', 'r3', '{']
['interface', 'ir3b', '10.2.0.103']
['}']"""

【问题讨论】:

  • 尝试将rule = zoneRule | hostRule | interfaceRule | interfaceRule2 | firewallRule | routerRule | endRule 重新排序为rule = zoneRule | hostRule | interfaceRule2 | interfaceRule | firewallRule | routerRule | endRule。此外,如果可能,请尝试使interface2 更具体,例如interfaceRule2 = interface + interfaceid + address + CaselessLiteral('nat')interfaceRule2 = interface + interfaceid + address + oneOf("nat ext ipv6 other1 other2")。另请查看 2.1.5 版本,包括 IPv4 和 IPv6 地址的 pyparsing_common 定义。

标签: python parsing firewall rules pyparsing


【解决方案1】:

如果您想匹配任意数量的带有特定分隔符的表达式,请使用PyParsing's delimitedList。默认情况下,它允许分隔符周围有空格;添加combine=True 不需要空格。

但是,如果你想在你的语法中允许可选项目,你应该只添加一个可选项目。对于您的界面规则,您可以替换:

interfaceRule = interface + interfaceid + address 
interfaceRule2 = interface + interfaceid + address + word

与:

interfaceRule = interface + interfaceid + address + Optional(word)

最后,您发布的代码的实际问题是您使用了| 运算符,它是MatchFirst 的简写形式。 MatchFirst 将按顺序尝试给定的选项,并返回匹配的第一个选项的结果。如果您改用Or,其简写形式是^ 运算符,那么它将尝试所有选项并返回具有最长的选项em> 匹配。

【讨论】:

  • Optional 是解决此问题的一个很好的建议,但可能需要比word 更具体,因为它匹配任何 alpha 单词组,其中可能包括前导 interface下一条防火墙规则。
  • 非常感谢您提供的许多解决方案,已经尝试了所有解决方案,并且重新排序规则完成了它的工作,实际上按照上面的评论使用 Optional(word) 被替换为单词“interface”所以使用ClasslessLiteral('nat') 是一种解决方法。唯一的问题是,如果我遇到的不仅仅是“nat”,手动将不得不添加这些文字。但问题是有答案的。非常感谢你 。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多