You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python提取Nessus XML文件中tag标签的内容?

Nessus XML解析:提取tag标签内容的解决方案

问题描述

拥有若干Nessus文件,因场景限制无法在Nessus内转换为CSV,使用Python的ElementTree库编写解析工具时,仅能提取ReportHost的name属性,无法获取<tag name="host-ip">1.1.1.1</tag>这类tag标签内的文本内容,当前代码如下:

mainTree = etree.parse(fileName)
root = mainTree.getroot()
for reportHost in root.iter('ReportHost'):
    hostIP.append(reportHost.get('name'))

解决方案

要提取tag标签内的文本,需要遍历ReportHost节点下的tag子元素,通过属性匹配定位目标标签后获取text属性。修改后的代码示例:

import xml.etree.ElementTree as etree

hostIP = []
fileName = "your_nessus_file.nessus"

mainTree = etree.parse(fileName)
root = mainTree.getroot()

for reportHost in root.iter('ReportHost'):
    # 遍历当前ReportHost下的所有tag标签
    for tag in reportHost.iter('tag'):
        # 匹配目标tag的name属性
        if tag.get('name') == 'host-ip':
            # 获取标签内的文本内容
            host_ip = tag.text
            hostIP.append(host_ip)
            # 每个主机通常只有一个host-ip,找到后可终止当前循环
            break

补充说明

  • 如果需要提取多个不同类型的tag(如host-name、operating-system),可以扩展条件判断,或使用XPath表达式直接定位:
    # 用XPath查找特定name的tag
    os_tag = reportHost.find(".//tag[@name='operating-system']")
    if os_tag:
        os_info = os_tag.text
    
  • 部分Nessus XML可能包含命名空间,若遇到标签无法匹配的情况,需先解析命名空间并在查询时指定(不过大部分常规Nessus导出文件无此问题)。

内容的提问来源于stack exchange,提问作者King

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:25:11