C++解析nmap xml输出以及类似的Boost xml_parser

C++ Parsing nmap xml output and similar with Boost xml_parser

本文关键字:xml Boost parser 解析 nmap 输出 C++      更新时间:2023-10-16

对于xml:

<?xml version="1.0" ?>
<?xml-stylesheet href="file:///usr/share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 5.21 scan initiated Tue Feb  3 12:01:07 2015 as: nmap -v -R -sP -PS80 -&#45;traceroute -oX /tmp/SCB_nmap_tcp_traceroute.xml 54.209.104.11 -->
<nmaprun scanner="nmap" args="nmap -v -R -sP -PS80 -&#45;traceroute -oX /tmp/SCB_nmap_tcp_traceroute.xml 54.209.104.11" start="1422964867" startstr="Tue Feb  3 12:01:07 2015" version="5.21" xmloutputversion="1.03">
<verbose level="1" />
<debugging level="0" />
<taskbegin task="Ping Scan" time="1422964867" />
<taskend task="Ping Scan" time="1422964867" extrainfo="1 total hosts" />
<taskbegin task="Parallel DNS resolution of 1 host." time="1422964867" />
<taskend task="Parallel DNS resolution of 1 host." time="1422964867" />
<taskbegin task="Traceroute" time="1422964867" />
<taskend task="Traceroute" time="1422964873" />
<host starttime="1422964867" endtime="1422964867"><status state="up" reason="reset"/>
<address addr="54.209.104.11" addrtype="ipv4" />
<hostnames>
<hostname name="ec2-54-209-104-11.compute-1.amazonaws.com" type="PTR"/>
</hostnames>
<trace port="80" proto="tcp">
<hop ttl="17" ipaddr="54.209.104.11" rtt="256.20" host="ec2-54-209-104-11.compute-1.amazonaws.com"/>
</trace>
<times srtt="256382" rttvar="192360" to="1025822" />
</host>
<runstats><finished time="1422964873" timestr="Tue Feb  3 12:01:13 2015" elapsed="6.48"/><hosts up="1" down="0" total="1" />
<!-- Nmap done at Tue Feb  3 12:01:13 2015; 1 IP address (1 host up) scanned in 6.48 seconds -->
</runstats></nmaprun>

我尝试使用Boost进行如下解析:

int main ( int, char ** )
try
{
        // Will hold file contents.
    stringstream contents;
        // Open the file for the shortest time possible.
    { ifstream file("./SCB_nmap_tcp_traceroute.xml", ios::binary);
            // Make sure we have something to read.
        if ( !file.is_open() ) {
            throw ("Could not open file.");
        }
            // Copy contents "as efficiently as possible".
        contents << file.rdbuf();
    }
        // Do something "useful" with the file contents.
    cout << contents.rdbuf();
    using boost::property_tree::ptree;
    ptree pt;
    read_xml(contents, pt);
        BOOST_FOREACH(ptree::value_type &v, pt.get_child("runstats"))
                cout<<"Found trace"<<endl;

我正在获取一个没有这样的节点,通过BOOST_FOREACH为"nmaprun"、"trace"answers"runstats"转储核心。请提供建议。

在引发'boost::exception_detail::clone_inpl>'的实例后调用terminatewhat():没有这样的节点(runstats)中止(堆芯转储)

在您的定义中:

BOOST_FOREACH(ptree::value_type &v, pt.get_child("runstats"))

您需要将根节点放在runstats之前,请尝试:

BOOST_FOREACH(ptree::value_type &v, pt.get_child("nmaprun.runstats"))