Nmap结果文件XML文件解析

对nmap扫描结果xml格式的文件进行解析,无需直接xml解析或读取,可直接使用模块:

1.nmapparser

安装:pip install nmapparser

Demo:

#!/usr/bin/env python
# Copyright (C) 2007 Guilherme Polo 
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
"""
A demo script showing how to use nmapparser.
"""

import sys
import re
from nmapparser import NmapParser

def usage():
    """Show demo usage."""
    print "Usage: %s xmlfile1.xml xmlfile2.xml ..." % __file__

def getaddress(str):
    reg=u"addr': '(.*?)'}"
    lister=re.compile(reg)
    mylist=re.findall(lister,str)
    #print mylist
    return mylist[0]


def main(args):
    parser = NmapParser()
    for xmlf in sys.argv[1:]:
        print "%s\nParsing %s" % ('*' * 75, xmlf)
        parser.parse(xmlf)

        if not parser.parsed:
            continue

        print "Options:", parser.options
        print "Finish time:", parser.runstats.finished.time

        h_stats = parser.runstats.hosts
        print "Hosts -> total %s, up: %s, down: %s" % (
            h_stats.total, h_stats.up, h_stats.down)

        for host in parser.host:
            print "Host options:", host.options

            if 'extraports' in  host.options:
                print "Host extraports:", host.ports.extraports

            print "Hostname:", host.hostnames
            print "HostIp:", getaddress(str(host.address))

            if 'ports' not in host.options or \
                'ports' not in host.ports.options:
                continue

            if 'script' in host.ports.ports[0].options:
                print
                print host.ports.ports[0].script[0].output
                print

            print "Host ports info:"
            for p in host.ports.ports:
                print "%20s%7s%9s%6s" % (getaddress(str(host.address)),p.portid, p.state, p.protocol)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(usage())
    main(sys.argv)

解析:

demo.py *.xml

结果输出:

Nmap结果文件XML文件解析_第1张图片

2.python-libnmap

安装:

pip install python-libnmap //copyright AnYun.ORG

Demo:

#!/usr/bin/env python

import argparse
from libnmap.process import NmapProcess
from libnmap.parser import NmapParser, NmapParserException

def parse_args():
    ''' Create the arguments '''
    parser = argparse.ArgumentParser()
    parser.add_argument("-x", "--nmapxml", help="Nmap XML file to parse")
    parser.add_argument("-l", "--hostlist", help="Host list file")
    return parser.parse_args()

def report_parser(report):
    ''' Parse the Nmap XML report '''
    for host in report.hosts:
        ip = host.address

        if host.is_up():
            hostname = 'N/A'
            # Get the first hostname (sometimes there can be multi)
            if len(host.hostnames) != 0:
                hostname = host.hostnames[0]

            print '[*] {0} - {1}'.format(ip, hostname)

            # Get the port and service
            # objects in host.services are NmapService objects
            for s in host.services:

                # Check if port is open
                if s.open():
                    serv = s.service
                    port = s.port
                    ban = s.banner

                    # Perform some action on the data
                    print_data(ip, port, serv, ban)

def print_data(ip, port, serv, ban):
    ''' Do something with the nmap data '''
    if ban != '':
        ban = ' -- {0}'.format(ban)
    print ip,port,serv,ban

    #print '    {0}: {1}{2}'.format(port, serv, ban)
    #print '    {0}: {1}{2}'.format(port, serv, ban)

def main():
    args = parse_args()
    report = NmapParser.parse_fromfile(args.nmapxml)
    report_parser(report)

main()

解析:

nmap-parser-dome.py -x  *.xml

结果输出:

Nmap结果文件XML文件解析_第2张图片

 

 

以上能基本解析了XML文件内容,若有其他需求,可参照修改偷懒

 

转载于:https://www.cnblogs.com/crac/p/8245734.html

你可能感兴趣的:(Nmap结果文件XML文件解析)