如何使用python来解析ossec规则xml

时间:2014-10-16 11:09:12

标签: python xml

我有一个ossec规则XML文件,内容如下:

<var name="SENSITIVE_DIRECTORY">^/root|^/proc|^/etc|^/$</var>
<var name="BAD_WORDS_OPS">failure|error|bad |fatal|failed|illegal |denied|refused|unauthorized</var>

<group name="local,ops,syslog,sudo,pam,">

  <rule id="101000" level="4">
     <if_sid>5715</if_sid>
     <srcip>!10.83.60.54</srcip>
     <srcip>!10.83.60.55</srcip> 
     <description>Except IPs approved.</description>
   </rule>
</group>

我正在尝试使用python来解析这个xml,但是我收到了这个错误:

xml.etree.ElementTree.ParseError: junk after document element: line 10, column 0

以下是我正在使用的代码:

  from xml.etree import ElementTree

  def read_xml(text):
      root = ElementTree.fromstring(text)
      lst_node = root.getiterator("person")
      print lst_node

  if __name__ == '__main__':
      read_xml(open("test.xml").read())

1 个答案:

答案 0 :(得分:2)

用这样的标签包装你的xml

import xml.etree.ElementTree as ET

def read_xml(text):
    root = ET.fromstring('<root>'+text+'</root>') # just wrap it with a root tag
    for el in root.iter('srcip'): # I changed the tag to srcip since your sample hasn't got "player"
        print el.text

if __name__ == '__main__':
    read_xml(open("yourfile.xml", "r").read())

!10.83.60.54
!10.83.60.55