微慑信息网

[原]Nmap结果文件XML文件解析

[VULSEE.COM]

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

1.nmapparser

安装:pip install nmapparser

Demo:

#!/usr/bin/env python
# Copyright (C) 2007 Guilherme Polo <[email protected]>
#
# 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

结果输出:

2.python-libnmap

安装:

pip install python-libnmap

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

结果输出:

 

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

赞(0) 打赏
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » [原]Nmap结果文件XML文件解析

评论 抢沙发

微慑信息网 专注工匠精神

微慑信息网-VulSee.com-关注前沿安全态势,聚合网络安全漏洞信息,分享安全文档案例

访问我们联系我们

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册