Example #1
0
    def nmap_specific_udp_scan(self, target, portlist, file_export = None):
        '''
        Runs nmap against specified UDP ports given in portlist argument

        Arguments: 
          - ``target`` ... IP or the range of IPs that need to be tested  
          - ``portlist`` ... list of ports, range of ports that need to be tested
                             either comma separated or hyphen 
          - ``file_export`` ... is an optional parameter the exports findings into a file

        Examples:
          nmap_specific_udp_scan <target> <portlist> <file-export>
        '''

        target = str(target)

        if file_export == None:
            nmproc = NmapProcess(target, '-p1-65535 -sV')
        else:
            cmd = '-sU -sV -p {0} -oN {1}'.format(portlist, file_export)
            nmproc = NmapProcess(target, cmd, safe_mode=False)

        rc = nmproc.run()
        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(nmproc.stderr))
        try: 
            parsed = NmapParser.parse(nmproc.stdout)
            print(parsed)
            self.results = parsed
        except NmapParserException as ne:
            print('EXCEPTION: Exception in parsing results {0}'.format(ne.msg))
Example #2
0
def scan():
    form = IPscannerForm()
    if form.validate_on_submit():
        ip = form.ip.data
        ip = str(ip)
        nm1 = NmapProcess(ip, options="-sn")
        nm1.run()
        parsed = NmapParser.parse(nm1.stdout)
        G = nx.Graph()
        nm2 = NmapProcess("www.baidu.com", options="--traceroute")
        nm2.run()
        collection = xml.etree.ElementTree.fromstring(nm2.stdout)
        nodes = collection.getiterator("hop")
        trace_list = []
        pre_node = ''
        for node in nodes:
            trace_list.append(node.attrib["ipaddr"])
            G.add_node(node.attrib["ipaddr"])
            if pre_node != '':
                G.add_edge(node.attrib["ipaddr"], pre_node)
            pre_node = node.attrib["ipaddr"]
        for host in parsed.hosts:
            if host.is_up():
                G.add_node(host.address)
                G.add_edge(host.address, trace_list[0])
        gra_json = json.dumps(G.adj)
        return render_template('result.html', gra_json=gra_json)
    return render_template('scan.html', form=form)
Example #3
0
    def nmap_default_scan(self, target, file_export=None):
        '''
        Runs a basic nmap scan on nmap's default 1024 ports. Performs the default scan
        - file_export is an optional param that exports the file to a txt file with the -oN flag

        Examples:
        | nmap default scan  | target | file_export |


        '''
        target = str(target)
        if file_export == None:
            nmproc = NmapProcess(target)
        else:
            nmproc = NmapProcess(target,
                                 '-oN {0}'.format(file_export),
                                 safe_mode=False)
        rc = nmproc.run()
        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(
                nmproc.stderr))
        try:
            parsed = NmapParser.parse(nmproc.stdout)
            print(parsed)
            self.results = parsed
        except NmapParserException as ne:
            print('EXCEPTION: Exception in Parsing results: {0}'.format(
                ne.msg))
Example #4
0
    def nmap_all_tcp_scan(self, target, file_export=None):
        print('AAAA')

        target = str(target)

        if file_export == None:
            nmproc = NmapProcess(target, '-p1-65535 -sV')
        else:
            cmd = '-p1-65535 -sV -oN {0}'.format(file_export)
            nmproc = NmapProcess(target, cmd, safe_mode=False)

        rc = nmproc.run()

        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(
                nmproc.stderr))

        try:
            parsed = NmapParser.parse(nmproc.stdout)
            print(parsed)

            nmap_print_results(this)

            self.results = parsed
        except NmapParserException as ne:
            print('EXCEPTION: Exception in Parsing results: {0}'.format(
                ne.msg))
Example #5
0
    def nmap_default_scan(self, target, file_export=None):
        target = str(target)

        if file_export == None:
            nmproc = NmapProcess(target, "-Pn -sV")
        else:
            nmproc = NmapProcess(target,
                                 '-oN {0}'.format(file_export),
                                 safe_mode=False)

        rc = nmproc.run()

        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(
                nmproc.stderr))

        try:
            parsed = NmapParser.parse(nmproc.stdout)

            self.results = parsed

            self.nmap_print_results()
        except NmapParserException as ne:
            print('EXCEPTION: Exception in Parsing results: {0}'.format(
                ne.msg))
Example #6
0
    def nmap_all_tcp_scan(self, target, file_export=None):
        '''
        Runs nmap scan against all TCP Ports with version scanning. Options used -Pn -sV -p1-65535
        Examples:
        | nmap default scan  | target | file_export |

        file_export is an optional param that exports the file to a txt file with the -oN flag
        '''
        target = str(target)
        if file_export == None:
            nmproc = NmapProcess(target, '-p1-65535 -sV')
        else:
            cmd = '-p1-65535 -sV -oN {0}'.format(file_export)
            nmproc = NmapProcess(target, cmd, safe_mode=False)
        rc = nmproc.run()
        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(
                nmproc.stderr))
        try:
            parsed = NmapParser.parse(nmproc.stdout)
            print(parsed)
            self.results = parsed
        except NmapParserException as ne:
            print('EXCEPTION: Exception in Parsing results: {0}'.format(
                ne.msg))
Example #7
0
 def nmap_specific_udp_scan(self, target, portlist, file_export=None):
     '''
     Runs nmap against specified UDP ports given in the portlist argument.
     Arguments:
         - ``target``: IP or the range of IPs that need to be tested
         - ``portlist``: list of ports, range of ports that need to be tested. They can either be comma separated or separated by hyphen
         example: 121,161,240 or 1-100
         - ``file_export``: is an optional param that exports the file to a txt file with the -oN flag
     Examples:
     | nmap specific udp scan  | target | portlist | file_export |
     '''
     target = str(target)
     if file_export == None:
         nmproc = NmapProcess(target, '-p1-65535 -sV')
     else:
         cmd = '-sU -sV -p {0} -oN {1}'.format(portlist, file_export)
         nmproc = NmapProcess(target, cmd, safe_mode=False)
     rc = nmproc.run()
     if rc != 0:
         raise Exception('EXCEPTION: nmap scan failed: {0}'.format(
             nmproc.stderr))
     try:
         parsed = NmapParser.parse(nmproc.stdout)
         print(parsed)
         self.results = parsed
     except NmapParserException as ne:
         print('EXCEPTION: Exception in parsing results: {0}'.format(
             ne.msg))
Example #8
0
    def nmap_os_services_scan(self, target, portlist=None, version_intense = 0, file_export = None):
        '''
        Runs
        Arguments:
            - ``target``: IP or the range of IPs that need to be tested
            - ``portlist``: list of ports, range of ports that need to be tested. They can either be comma separated or separated by hyphen
            example: 121,161,240 or 1-100
            - ``version_intense``: Version intensity of OS detection
            - ``file_export``: is an optional param that exports the file to a txt file with the -oN flag
        Examples:
        | nmap os services scan  | target | portlist | version_intense | file_export |
        '''
        target = str(target)
        if portlist:
            nmap_proc_cmd = "-Pn -sV --version-intensity {0} -p {1}".format(version_intense, portlist)
        else:
            nmap_proc_cmd = "-Pn -sV --version-intensity {0}".format(version_intense)

        if file_export:
            nmap_proc_cmd += " -oN {0}".format(file_export)

        nmproc = NmapProcess(target, nmap_proc_cmd, safe_mode=False)
        rc = nmproc.run()
        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(nmproc.stderr))
        try:
            parsed = NmapParser.parse(nmproc.stdout)
            print parsed
            self.results = parsed
        except NmapParserException as ne:
            print 'EXCEPTION: Exception in parsing results: {0}'.format(ne.msg)
Example #9
0
 def scanByNmap(self, target, policy):
     runtime = 0
     try:
         nmap_proc = NmapProcess(targets=target,
                                 options=policy,
                                 safe_mode=True)
         nmap_proc.run_background()
         while nmap_proc.is_running():
             if runtime >= self.nmap_timeout:
                 nmap_proc.stop()
                 if self.output_mode != "silent":
                     print self.R + u'\n[x] scan_host {} timeout...'.format(
                         target) + self.W
                 break
             else:
                 if self.output_mode != "silent":
                     sys.stdout.write(
                         u'\033[1;34m[~] scan_host is {},scan progress is {}%({} sec)\n\033[0m'
                         .format(target, nmap_proc.progress, runtime))
                     sys.stdout.flush()
                 sleep(5)
                 runtime += 5
         if nmap_proc.is_successful() and nmap_proc.stdout:
             self.parserReport(nmap_proc.stdout)
     except Exception as e:
         print e
Example #10
0
def celery_nmap_scan(targets, options):
    def status_callback(nmapscan=None, data=''):
        current_task.update_state(state='PROGRESS',
                                  meta={
                                      'done': nmapscan.progress,
                                      'etc': nmapscan.etc
                                  })

    if '/' in targets:
        if isinstance(targets, unicode):
            _network = ipaddress.ip_network(targets)
        else:
            _network = ipaddress.ip_network(targets.encode('unicode'))
        targets = [str(ip) for ip in _network.hosts()]
    else:
        targets = targets.encode('ascii', 'ignore')

    nm = NmapProcess(targets, options, event_callback=status_callback)
    rc = nm.sudo_run()

    if rc == 0 and nm.stdout:
        r = nm.stdout
    else:
        r = nm.stderr

    return {'rc': rc, 'report': r}
Example #11
0
    def run(self):

        # Wait until all active devices have been populated during boot
        time.sleep(30)

        while 1:
            ip_list = ','.join(homenet.hosts.keys())

            log.debug('FG-INFO: Port scan started')

            nm = NmapProcess(targets=ip_list, options='-sU -sS --min-rate 5000 --max-retries 1 --max-rtt-timeout 100ms -p1-10000 ')
            nm.run()

            try:
                nmap_report = NmapParser.parse(nm.stdout)

                with lock:
                    for host in nmap_report.hosts:
                        if host.address in homenet.hosts.keys():
                            for serv in host.services:
                                if (serv.protocol == 'tcp') and (serv.state == 'open'):
                                    if serv.port not in homenet.hosts[host.address].tcp_ports:
                                        homenet.hosts[host.address].tcp_ports.append(serv.port)
                                if (serv.protocol == 'udp') and (serv.state == 'open'):
                                    if serv.port not in homenet.hosts[host.address].udp_ports:
                                        homenet.hosts[host.address].udp_ports.append(serv.port)
            except Exception as e:
                log.debug('FG-WARN: ' + str(e.__doc__) + " - " + str(e))

            log.debug('FG-INFO: Port scan finished')

            time.sleep(86400)
Example #12
0
    def _process(self, session):
        nmproc = NmapProcess("10.0.0.1", "-sT")
        parsed = None
        rc = nmproc.run()
        if rc != 0:
            logging.critical("NMAP Scan failed: {0}".format(nmproc.stderr))

        try:
            parsed = NmapParser.parse(nmproc.stdout)
        except NmapParserException as e:
            logging.critical("NMAP Parse failed: {0}".format(e.msg))

        if parsed is not None:
            for host in parsed.hosts:
                if len(host.hostnames):
                    tmp_host = host.hostnames.pop()
                else:
                    tmp_host = host.address

                print("Nmap scan report for {0} ({1})".format(
                    tmp_host,
                    host.address))
                print("Host is {0}.".format(host.status))
                print("  PORT     STATE         SERVICE")

                for serv in host.services:
                    pserv = "{0:>5s}/{1:3s}  {2:12s}  {3}".format(
                            str(serv.port),
                            serv.protocol,
                            serv.state,
                            serv.service)
                    if len(serv.banner):
                        pserv += " ({0})".format(serv.banner)
                    print(pserv)
Example #13
0
 def udp_scan(self, udp_start, udp_end):
     '''
     udp端口扫描
     :param udp_start:
     :param udp_end:
     :return: json
     '''
     nmap_proc = NmapProcess(targets=self.ip,
                             options='-sU -e ' + str(self.iface) + ' -p ' +
                             str(udp_start) + "-" + str(udp_end))
     nmap_proc.run_background()
     while nmap_proc.is_running() and stop == 0:
         current = float(nmap_proc.progress) * self.udp_total * 0.01
         self.udp_done.put(current)
         time.sleep(3)  # 3秒更新一次百分比
     if stop == 1:
         return
     ScanEngine = nmap.PortScanner()
     res = ScanEngine.analyse_nmap_xml_scan(nmap_proc.stdout)
     udp_ports = []
     if dict(res)['scan'] and res:
         ret = dict(res)['scan'][self.ip]
         if 'udp' in ret:
             udp_ports = ret['udp']
     for port in udp_ports:
         if str(udp_ports[port]['name']) and 'open' in str(
                 udp_ports[port]["state"]):
             self.result.put({
                 "ip": self.ip,
                 "port": str(port),
                 "protocol": "UDP",
                 "service": str(udp_ports[port]['name']),
                 "state": str(udp_ports[port]["state"])
             })
     self.udp_done.put(self.udp_total)
Example #14
0
def nmap_scan(hosts):
    '''
    Do Nmap scan
    '''
    # -sV is included by default in NmapProcess nmap cmd
    # To add more:  options = '-T4 -sU -p-'
    #                 hosts = ['192.168.0.1', '192.168.0.2']
    #nmap_args = '-T4 -sV -sS -pU:161,137,139'# -sS -sU --top-ports'
    nmap_args = '-T4 -sS -sV --max-rtt-timeout 100ms --max-retries 3'
    print '[*] Running: nmap {0} -iL <hostlist>'.format(nmap_args)
    nmap_proc = NmapProcess(targets=hosts, options=nmap_args)
    #rc = nmap_proc.sudo_run()
    rc = nmap_proc.sudo_run_background()
    while nmap_proc.is_running():
        print("[*] Nmap progress: {1}%".format(nmap_proc.etc, nmap_proc.progress))
        time.sleep(2)

    xml = nmap_proc.stdout

    try:
        report = NmapParser.parse(nmap_proc.stdout)
    except NmapParserException as e:
        print 'Exception raised while parsing scan: {0}'.format(e.msg)
        sys.exit()

    return report
Example #15
0
def nmap_scanning():
    nm = NmapProcess(get_ip(), options='')
    rc = nm.run()

    if nm.rc == 0:
        try:
            oldrep = NmapParser.parse_fromfile('old.xml')
            newrep = NmapParser.parse(nm.stdout)
        except:
            print('[-] Not found: old.xml')
            q = open('old.xml', 'w')
            q.write(nm.stdout)
            q.close()
            print('[+] Create new: old.xml')
            exit()
    else:
        print(nm.stderr)
    print('[+] Nmap scan complete')

    q = open('old.xml', 'w')
    q.write(nm.stdout)
    q.close()

    print('[+] Nmap file save as: old.xml')
    return (newrep, oldrep)
Example #16
0
    def nmap_os_services_scan(self,
                              target,
                              portlist=None,
                              version_intense=0,
                              file_export=None):
        target = str(target)

        if portlist:
            nmap_proc_cmd = '-Pn -sV --version_intensity {0} -p {1}'.format(
                portlist, version_intense)
        else:
            nmap_proc_cmd = '-Pn -sV --version_intensity {0}'.format(
                version_intense)

        if file_export:
            nmap_proc_cmd += " -oN {0}".format(file_export)

        nmproc = NmapProcess(target, cmd, safe_mode=False)

        rc = nmprocess.run()

        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(
                nmprocess.stderr))

        try:
            parsed = NmapParser.parse(nmprocess.stdout)
            print(parsed)

            self.results = parsed
        except NmapParserException as ne:
            print('EXCEPTION: Exception in parsing results: {0}'.format(
                ne.msg))
Example #17
0
 def nmap_cmd(self, tgt, cmd):
     """hello"""
     nmap_proc = NmapProcess(targets=tgt, options=cmd)
     nmap_proc.run()
     xml_msg = nmap_proc.stdout
     nmap_report = NmapParser.parse(xml_msg)
     return nmap_report
Example #18
0
 def port_scan(self, ip):
     process = NmapProcess(targets=ip,
                           options="-sT",
                           event_callback=None,
                           safe_mode=None,
                           fqp=None)
     rc = process.run()
     index = 0
     port = []
     proto = []
     state = []
     service = []
     if rc != 0:
         return False
     try:
         parser = NmapParser.parse(process.stdout)
     except NmapParserException:
         print("Exception Network Error")
     for host in parser.hosts:
         for serv in host.services:
             port.append(serv.port)
             proto.append(serv.protocol)
             state.append(serv.state)
             service.append(serv.service)
             index += 1
     return port, proto, state, service
Example #19
0
    def nmap_os_services_scan(self, target, portlist=None, version_intense = 0, file_export = None):
        '''
        Runs 
        Arguments:
            - ``target``: IP or range of IPs that need to be tested
            - ``portlist``: list of ports, range of ports that need be tested
            - ``version_intense``: Version intensity of OS detection
            - ``file_export``: is an optional parameter to export output into a file
        Examples:
            nmap_os_services_scan <target> <port_list> <version_intense> <file_export>
        '''
        target = str(target)

        if portlist:
            nmap_proc_cmd = "-Pn -sV --version-intensity {0} -p {1}".format(portlist, version_intense)
        else:
            nmap_proc_cmd = "-Pn -sV --version-intensity {0}".format(portlist)

        if file_export:
            nmap_proc_cmd += "-oN {0}".format(file_export)

        nmproc = NmapProcess(target, nmap_proc_cmd, safe_mode=False)
        rc = nmproc.run()

        if rc != 0:
            raise Exception('EXCEPTION: nmap scan failed: {0}'.format(nmproc.stderr))
        try: 
            parsed = NmapParser.parse(nmproc.stdout)
            print(parsed)
            self.result = parsed
        except NmapParserException as ne:
            print('EXCEPTION: Exception in parsing results: {0}'.format(ne.msg))
Example #20
0
    def test_check_targets(self):
        invalid_target_tests = [{"a": "bba"}, 5]
        valid_target_tests = [
            {
                "value": "127.0.0.1, 1.1.1.1,     2.20.202",
                "size": 3
            },
            {
                "value": ["127.0.0.1", "1.1.1.1", "2.20.202.2"],
                "size": 3
            },
            {
                "value": ["     127.0.0.1", "  1.1.1.1"],
                "size": 2
            },
            {
                "value": "     127.0.0.1,      1.1.1.1  , a",
                "size": 3
            },
        ]
        for vtarget in valid_target_tests:
            nmapobj = NmapProcess(targets=vtarget["value"], options="-sP")
            self.assertEqual(vtarget["size"], len(nmapobj.targets))

        for vtarget in invalid_target_tests:
            self._assertRaisesRegex(
                Exception,
                "Supplied target list should be either a string or a list",
                NmapProcess,
                targets=vtarget,
                options="-sP",
            )
Example #21
0
def os_fingerprint(target_ip):
    # param source_ip: 源站IP,不填则不做操作系统类型(linux|windows .etc)指纹检测
    if not target_ip:
        return None
    report = None
    nm = NmapProcess(targets=target_ip, options='-O')
    rc = nm.run()
    if rc != 0:
        return report
    try:
        report = NmapParser.parse(nm.stdout)
    except:
        pass
    os_name = None
    if report:
        host = report.hosts[0]
        if host.os_fingerprinted:
            for osm in host.os.osmatches:
                if osm.accuracy >= 90:  # 符合某操作系统指纹几率大于90%, 就取该指纹
                    os_name = osm.name
                break
    if not os_name:
        return 'unknown'

    if re.search('linux', os_name, re.I):
        return 'linux'
    elif re.search('windows', os_name, re.I):
        return 'windows'
    else:
        return 'unknown'
Example #22
0
def nmap_scan(targets):
    # Nmap scan with service detection (-sV), script scanning (-sC) on all
    # ports (-p-) and agressive timing (-T4)
    nmap_proc = NmapProcess(targets,
                            options='-sV -sC -p- -T4',
                            safe_mode=False)
    nmap_proc.run_background()

    # Checks nmap progress every 30 seconds
    print('Nmap start at {0}'.format(datetime.today().ctime()))
    while nmap_proc.is_running():
        nmaptask = nmap_proc.current_task
        if nmaptask:
            print("Task {0} {1} ({2}): Progress: {3}%".format(
                len(nmap_proc.tasks) + 1, nmaptask.name, nmaptask.status,
                nmaptask.progress))
        sleep(30)

    print(nmap_proc.summary)

    try:
        report = NmapParser.parse(nmap_proc.stdout)
    except NmapParserException as e:
        print('Exception raised while parsing scan: {0}'.format(e.msg))

    if report.hosts_total == 0:
        print('No hosts discovered')
        sys.exit()

    return report
Example #23
0
 def start(self):
     ''' Start Discovery '''
     logs = core.logs.Logger(config=self.config, proc_name="discovery.nmap")
     logger = logs.getLogger()
     logger = logs.clean_handlers(logger)
     logger.info("Starting scan of environment")
     try:
         nmap = NmapProcess(
             self.config['discovery']['plugins']['nmap']['target'],
             options=self.config['discovery']['plugins']['nmap']['flags'])
     except Exception as e:
         raise Exception("Failed to execute nmap process: {0}".format(
             e.message))
     up = []
     while True:
         nmap.run()
         nmap_report = NmapParser.parse(nmap.stdout)
         for scanned_host in nmap_report.hosts:
             if "up" in scanned_host.status and scanned_host.address not in up:
                 up.append(scanned_host.address)
                 logger.debug("Found new host: {0}".format(
                     scanned_host.address))
                 if self.dbc.new_discovery(ip=scanned_host.address):
                     logger.debug(
                         "Added host {0} to discovery queue".format(
                             scanned_host.address))
                 else:
                     logger.debug(
                         "Failed to add host {0} to discovery queue".format(
                             scanned_host.address))
         logger.debug("Scanned {0} hosts, {1} found up".format(
             len(nmap_report.hosts), len(up)))
         time.sleep(self.config['discovery']['plugins']['nmap']['interval'])
     return True
Example #24
0
def do_scan(netRange):
    parsed = None
    for i in netRange:
        scanner = NmapProcess(i, options="-sV --top-ports 100")
        rc = scanner.run()

        if scanner.rc == 0:
            parsed = NmapParser.parse(scanner.stdout)
            for host in parsed.hosts:
                if len(host.hostnames):
                    tmp_host = host.hostnames.pop()
                else:
                    tmp_host = host.address

                print("Nmap Scan Report for {0} ({1})".format(
                    tmp_host, host.address))
                print("Host is {0}".format(host.status))
                print("  PORT     STATE         SERVICE")
                for serv in host.services:
                    pserv = "{0:>5s}/1{1:3s}  {2:12s}  {3}".format(
                        str(serv.port), serv.protocol, serv.service)
                    if len(serv.banner):
                        pserv += " ({0})".format(serv.banner)
                print pserv
        else:
            print scanner.stderr
Example #25
0
 def test_exec(self):
     nmapobj = NmapProcess(targets="127.0.0.1", options="-sP")
     rc = nmapobj.run()
     parsed = NmapParser.parse(nmapobj.stdout)
     self.assertEqual(rc, 0)
     self.assertGreater(len(nmapobj.stdout), 0)
     self.assertIsInstance(parsed, NmapReport)
Example #26
0
    def do_scan(self, targets, options):
        """
        start a new nmap scan on localhost with some specific options
        :param targets:
        :param options:
        :return:
        """
        logger.info('do scan %s %s' % (targets, options))
        parsed = None
        if isinstance(options, basestring):
            options = options.encode('utf-8')
        if isinstance(targets, basestring):
            targets = targets.encode('utf-8')
        nmproc = NmapProcess(targets, options)
        rc = nmproc.run()
        if rc != 0:
            logger.error("nmap scan failed: {0}".format(nmproc.stderr))
        # print(type(nmproc.stdout))

        try:
            parsed = NmapParser.parse(nmproc.stdout)
        except NmapParserException as e:
            logger.error("Exception raised while parsing scan: {0}".format(e.msg))

        self.done_data[targets] = parsed
        return parsed
Example #27
0
    def _update_info(self):
        """ Scans the network for devices.
            Returns boolean if scanning successful. """
        if not self.success_init:
            return False

        _LOGGER.info("Scanning")

        options = "-F --host-timeout 5"
        exclude_targets = set()
        if self.home_interval:
            now = datetime.now()
            for host in self.last_results:
                if host.last_update + self.home_interval > now:
                    exclude_targets.add(host)
            if len(exclude_targets) > 0:
                target_list = [t.ip for t in exclude_targets]
                options += " --exclude {}".format(",".join(target_list))

        nmap = NmapProcess(targets=self.hosts, options=options)

        nmap.run()

        if nmap.rc == 0:
            if self._parse_results(nmap.stdout):
                self.last_results.extend(exclude_targets)
        else:
            self.last_results = []
            _LOGGER.error(nmap.stderr)
            return False
Example #28
0
def _run_scan(ips, now):
    nmap = NmapProcess(ips)
    rc = nmap.run()
    if rc != 0:
        logging.error("nmap failed with error {}".format(rc))
        return

    try:
        report = NmapParser.parse(nmap.stdout)
    except NmapParserException as e:
        logging.error("nmap parsing error? " + str(e))
        return

    ret = []
    for host in report.hosts:
        ports = ['{}/{}'.format(s.port, s.state) for s in host.services]
        obs = {
            'time': now.isoformat(),
            'source': host.address,
            'ports': ', '.join(ports),
            'info_type': 'services',
            'result': '',
        }
        ret.append(obs)

    return ret
    def _generate_nmap_dict_report(self, targets, options, request):
        """
        Executes the Nmap tool to scan/analyze a list of hosts (IPs) with the specific
        (parameters) options.

        :param targets: List of hosts (IPs) to scan/analyze.
        :param options: Options required to execute Nmap tool.
        :param request: The request message.
        :return: The Nmap output information (formatted) based on the original Nmap XML report
        information.
        """

        # Create Nmap process and run it
        nmproc = NmapProcess(targets, options)

        try:
            # Run the Nmap process
            nmproc.run()

            # Generate report
            nmap_report = NmapParser.parse(nmproc.stdout)

            # Parse Nmap report
            parsed_report = self._parse_nmap_xml_report(nmap_report)

            # Return the parse  Nmap report
            return parsed_report
        except Exception as ex:
            logger.exception("Nmap scan failed: {0}".format(nmproc.stderr))
            err_res = ErrorResponse(request, MessageUtils.encode(str(ex)))
            self._app.client.send_response(err_res)
Example #30
0
def fingerprint_hostname(hostname):
    if hostname[:3]=="192":
        nmproc = NmapProcess(targets=hostname, options="-O")
        rc=nmproc.run()
        parsed = NmapParser.parse(nmproc.stdout)
        host = parsed.hosts[0]
        os_match = []
        if host.os_fingerprinted:
            fingerprint = host.os.osmatches
            for osm in host.os.osmatches:
                #print("Found Match:{0} ({1}%)".format(osm.name, osm.accuracy))
                fingerprint = str(osm.osclasses).replace("\n","").replace("   |__", "").replace("\r","").replace("[","").replace("]","")
                #for osc in osm.osclasses:
                #    os_match.append(str(osc.description))
                    #print("\tOS Class: {0}".format(osc.description))
        else:
            fingerprint = None
        services = []
        for serv in host.services:
            services.append(str(serv.port) + "/" + str(serv.service))
            #print("Open ports:", services)

        return [fingerprint, services]
    else:
        return ["external", "unknown"]