def writeInfoToXml(filename, config_id, obj_name):
from xml.dom.minidom import Document
'''
eg:
<modify_config config_id="{}">
<nvt_selection>
<family>Web Servers</family>
<nvt oid="{}"/>
<family>Denial of Service</family>
<nvt oid="{}"/>
<family>General</family>
<nvt oid="{}"/>
</nvt_selection>
</modify_config>
'''
# 创建dom文档
doc = Document()
# 创建根节点
modify_node = doc.createElement('modify_config')
# 修改或添加节点中元素内容
modify_node.setAttribute("config_id", config_id)
# 根节点插入dom树
doc.appendChild(modify_node)
# 每一组信息先创建节点<order>,然后插入到父节点<modify_node>下
nvtSlect = doc.createElement('nvt_selection')
modify_node.appendChild(nvtSlect)
# 从数据库查询需要扫描的项
vulnerData = nova_get_vulnerdata_from_db(obj_name)
# 依次将vulnerData中的每一组元素提取出来,创建对应节点并插入dom树
for idx, sub_data in enumerate(vulnerData):
for name, oid_list in sub_data.items():
# 创建节点<family>
family = doc.createElement('family')
# 创建<family>下的文本节点
family_text = doc.createTextNode(name)
# 将文本节点插入到<family>下
family.appendChild(family_text)
# 将<family>插入到父节点<nvtSlect>下
nvtSlect.appendChild(family)
for oid in oid_list:
# 创建nvt节点
nvt_node = doc.createElement('nvt')
# 修改或添加节点中元素内容
nvt_node.setAttribute("oid", oid)
# 将nvt节点插入到父节点nvtSlect
nvtSlect.appendChild(nvt_node)
cmd = "rm -rf {}".format(filename)
subprocess.check_output(cmd, shell=True)
# 将dom对象写入本地xml文件
with open(filename, 'w') as f:
doc.writexml(f, indent='',addindent='\t',newl='\n',encoding='UTF-8')