Пример #1
0
 def do_scan(self, target, options="-n -sS --host-timeout 600 --open"):
     # 记录结果
     db = DB()
     nmproc = NmapProcess(target, options)
     nmproc.run_background()
     while nmproc.is_running():
         print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
             nmproc.etc, nmproc.progress))
         time.sleep(2)
     print("rc: {0} output: {1}".format(nmproc.rc, nmproc.summary))
     try:
         # 创建文件名
         md5 = hashlib.md5()
         md5.update(target)
         hash = md5.hexdigest()
         # with(open("data/nmap/" + hash + ".xml", "w")) as f:
         #     f.write(nmproc.stdout)
     except NmapParserException as e:
         print("Exception raised while parsing scan: {0}".format(e.msg))
     # 扫描完成,解析结果
     print {"status": 1, "result": hash}
     db.Nmap.update_one({"target": target},
                        {"$set": {
                            "status": 1,
                            "result": hash
                        }})
Пример #2
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)
Пример #3
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
Пример #4
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
Пример #5
0
def run_nmap_scan(scan_targets, scan_options):
    '''
    Accepts scan targets and scan options for NmapProcess and launches scan
    Prints scan status updates and summary to stdout
    Returns NmapProcess object for further use
    
    TODO - catch keyboard interrupts and kill tasks so we can exit gracefully!
            nmap_proc.stop does not appear to fully kill threads in script scans
            so program will continue to execute but leaves an orphaned nmap process
    '''
    status_update_interval = 5

    #Check for sudo and disable scan options that require root
    if os.getuid() != 0:
        logging.warn(
            "Certain nmap scans require root privileges (SYN, UDP, ICMP, etc)..."
        )
        logging.warn(
            "Disabling incompatible scan types and OS / service version detection options if enabled"
        )
        scan_options = scan_options.replace("-sS", "-sT")
        scan_options = scan_options.replace("-sU", "")
        scan_options = scan_options.replace("-sP", "")
        scan_options = scan_options.replace("-sn", "")
        scan_options = scan_options.replace("-sV", "")
        scan_options = scan_options.replace("-O", "")

    nmap_proc = NmapProcess(targets=scan_targets, options=scan_options)
    print "Running scan command:\n" + nmap_proc.command
    nmap_proc.run_background()

    while nmap_proc.is_running():
        try:
            time.sleep(status_update_interval)

            if nmap_proc.progress > 0:

                #Nmap only updates ETC periodically and will sometimes return a result that is behind current system time
                etctime = datetime.datetime.fromtimestamp(int(nmap_proc.etc))
                systime = datetime.datetime.now().replace(microsecond=0)
                if etctime < systime:
                    etctime = systime
                timeleft = etctime - systime
                print("{0} Timing: About {1}% done; ETC: {2} ({3} remaining)".
                      format(nmap_proc.current_task.name, nmap_proc.progress,
                             etctime, timeleft))
        except KeyboardInterrupt:
            print "Keyboard Interrupt - Killing Current Nmap Scan!"
            nmap_proc.stop()

    if nmap_proc.rc == 0:
        print nmap_proc.summary + "\n"
    else:
        print nmap_proc.stderr + "\n"

    return nmap_proc
Пример #6
0
      def _run_scan(self):
          nmap_proc = NmapProcess(targets=self._target, options="-Pn -sT -sU -p "+self._port)
          nmap_proc.run_background()
          while nmap_proc.is_running():
              print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nmap_proc.etc,
                                                             nmap_proc.progress))
              sleep(2)

          if nmap_proc.rc != 0:
             print("Nmap scan failed: {0}".format(nmap_proc.stderr))
             sys.exit(2)
          else:
             return nmap_proc
Пример #7
0
def run_nmap_scan(scan_targets, scan_options):
    '''
    Accepts scan targets and scan options for NmapProcess and launches scan
    Prints scan status updates and summary to stdout
    Returns NmapProcess object for further use
    
    TODO - catch keyboard interrupts and kill tasks so we can exit gracefully!
            nmap_proc.stop does not appear to fully kill threads in script scans
            so program will continue to execute but leaves an orphaned nmap process
    '''
    status_update_interval = 5
    
    #Check for sudo and disable scan options that require root
    if os.getuid()!=0:
        logging.warn("Certain nmap scans require root privileges (SYN, UDP, ICMP, etc)...")
        logging.warn("Disabling incompatible scan types and OS / service version detection options if enabled")
        scan_options = scan_options.replace("-sS", "-sT")
        scan_options = scan_options.replace("-sU", "")
        scan_options = scan_options.replace("-sP", "")
        scan_options = scan_options.replace("-sn", "")
        scan_options = scan_options.replace("-sV", "")
        scan_options = scan_options.replace("-O", "")
    
    nmap_proc = NmapProcess(targets=scan_targets, options=scan_options)
    print "Running scan command:\n"+nmap_proc.command
    nmap_proc.run_background()
    
    while nmap_proc.is_running():
        try:
            time.sleep(status_update_interval)
            
            if nmap_proc.progress > 0:
                
                #Nmap only updates ETC periodically and will sometimes return a result that is behind current system time
                etctime = datetime.datetime.fromtimestamp(int(nmap_proc.etc))
                systime = datetime.datetime.now().replace(microsecond=0)
                if etctime < systime:
                    etctime = systime
                timeleft = etctime - systime
                print("{0} Timing: About {1}% done; ETC: {2} ({3} remaining)".format(nmap_proc.current_task.name, nmap_proc.progress, etctime, timeleft))
        except KeyboardInterrupt:
            print "Keyboard Interrupt - Killing Current Nmap Scan!"
            nmap_proc.stop()
        
    if nmap_proc.rc == 0:
        print nmap_proc.summary + "\n"
    else:
        print nmap_proc.stderr + "\n"
    
    return nmap_proc
Пример #8
0
 def do_scan(self):
     """scan start flag"""
     if(self._flg_is_scanning != True):
         self._flg_is_scanning = True
     if(self._flg_scan_finished != False):
         self._flg_scan_finished = False
     """运行次数初始化"""
     trycnt = 0
     while True:
         """运行时间初始化"""
         runtime = 0
         if trycnt >= self.retrycnt:
             print '-' * 50
             return 'retry overflow'
         try:
             nmap_proc = NmapProcess(targets=self.targets,options=self.options,safe_mode=False)
             self._flg_is_scanning = True    
             nmap_proc.run_background()
             while(nmap_proc.is_running()):
                 """运行超时,结束掉任务,休息1分钟,再重启这个nmap任务"""
                 if runtime >= self.timeout:
                     print '-' * 50
                     print "timeout....terminate it...."
                     nmap_proc.stop()
                     """休眠时间"""
                     sleep(60)
                     trycnt += 1
                     break
                 else:
                     print 'running[%ss]:%s' %(runtime,nmap_proc.command)
                     sleep(5)
                     runtime += 5
             if nmap_proc.is_successful():
                 """scan finished flag"""
                 if(self._flg_is_scanning != False):
                     self._flg_is_scanning = False
                 if(self._flg_scan_finished != True):
                     self._flg_scan_finished = True
                     
                 print '-' * 50
                 print nmap_proc.summary
                 return nmap_proc.stdout
         except Exception,e:
             print e
             trycnt +=1
             if trycnt >= retrycnt:
                 print '-' * 50
                 print 'retry overflow'
                 return e
    def run_nmap_scan(self):
        parsed = None
        nmap_proc = NmapProcess(targets="10.10.10.3", options="")
        nmap_proc.run_background()

        while nmap_proc.is_running():
            print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
                nmap_proc.etc, nmap_proc.progress))
        sleep(2)

        nmap_report = NmapParser.parse(nmap_proc.stdout)

        nmap_results = NmapResults()
        nmap_results.add_hosts(nmap_report)
        return nmap_results
Пример #10
0
def nmap_scan(ip,ports,taskid):
    nmapscan.objects.create(ip=ip,task_id=taskid)
    result = nmapscan.objects.get(task_id=taskid)
    nmap_proc = NmapProcess(targets=ip, options='-sV -p  '+ports)
    nmap_proc.run_background()

    while nmap_proc.is_running():
        result.rate = str(nmap_proc.progress)
        result.save()
        time.sleep(2)  # 两秒更新一次百分比
    result.endtime = timezone.now()
    result.save()

    nm = nmap.PortScanner()

    print(nm.analyse_nmap_xml_scan(nmap_proc.stdout))
Пример #11
0
def do_scan(targets, options):
    parsed = None
    nmap_proc = NmapProcess(targets="scanme.nmap.org",
                            options="-sS -sV -sC -O -nvvv -T4 -Pn")
    nmap_proc.run_background()
    while nmap_proc.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
            nmap_proc.etc, nmap_proc.progress))
        sleep(2)

    print("rc: {0} output: {1}".format(nmap_proc.rc, nmap_proc.summary))
    try:
        parsed = NmapParser.parse(nmap_proc.stdout)
    except NmapParserException as e:
        print("Exception raised while parsing scan: {0}".format(e.msg))

    return parsed
Пример #12
0
def default_scan(target_path):

    # config parameters
    sleep_interval = 10

    # start scan
    target_list = read_targets(target_path)

    # heavy scan
    # nmap_proc = NmapProcess(targets=target_list, options="-sS -n -PE -PP -PM -PO -PS21,22,23,25,80,113,31339 -PA80,"
    #                                                               "113,443,10042 -O -T4 -p-")
    # light scan
    nmap_proc = NmapProcess(
        targets=target_list,
        options="-PE -PP -PM -PO -PS21,22,23,25,80,113,31339 -PA80,"
        "113,443,10042 -O -T4")

    # debug info
    print("scan target:")
    print(target_list)
    print("command:")
    print(nmap_proc.command)

    nmap_proc.run_background()
    while nmap_proc.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
            nmap_proc.etc, nmap_proc.progress))
        time.sleep(sleep_interval)

    print("rc: {0} output: {1}".format(nmap_proc.rc, nmap_proc.summary))

    # save to file
    time_label = time.strftime("%Y%m%d%H%M%S", time.localtime())
    with open('nmap_scan_' + time_label + '.xml', 'w') as f:
        f.write(nmap_proc.stdout)
    f.close()

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

    print_scan(nmap_report)

    return nmap_report
Пример #13
0
def do_nmap_scan(targets, port):
    # 运行次数初始化
    trycnt = 0
    options = '-sT -P0 -sV -O --script=banner -p T:' + port.strip()
    while True:
        # 运行时间初始化
        runtime = 0

        if trycnt >= retrycnt:
            print '-' * 50
            return 'retry overflow'

        try:
            nmap_proc = NmapProcess(targets=targets,
                                    options=options,
                                    safe_mode=False,
                                    fqp='/usr/bin/nmap')
            nmap_proc.run_background()

            while nmap_proc.is_running():
                if runtime >= timeout:  # 运行超时,结束掉任务,休息1分钟, 再重启这个nmap任务
                    print '-' * 50
                    print "* timeout. terminate it..."
                    nmap_proc.stop()
                    # 休眠时间
                    sleep(60)
                    trycnt += 1
                    break
                else:
                    print 'running[%ss]:%s' % (runtime, nmap_proc.command)
                    sleep(5)
                    runtime += 5
            if nmap_proc.is_successful():
                print '-' * 50
                print nmap_proc.summary
                return nmap_proc.stdout

        except Exception, e:
            # raise e
            print e
            trycnt += 1
            if trycnt >= retrycnt:
                print '-' * 50
                print '* retry overflow'
                return e
Пример #14
0
def nmap_scan(target, commands):
    nm = NmapProcess(target, commands)
    #change to sudo_run(run_as='root') to run syn scans
    nm.run_background()
    command = nm.get_command_line()
    print(command)
    while nm.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
            nm.etc, nm.progress))
        sleep(1)
    nmap_report = NmapParser.parse(nm.stdout)
    for host in nmap_report.hosts:

        if host.status == 'up':
            for serv in host.services:
                # if serv.port == 'open':
                service_check(host, serv)
    print("Primary Scan Completed \n")
Пример #15
0
def nmap_scan(ip,ports,taskid):
    scanIP.objects.get_or_create(ip=ip,task_id=taskid,scantime=datetime.datetime.now())
    scan_ip_info.objects.filter(ipfor_id=scanIP.objects.get(ip=ip).id).delete()
    result = scanIP.objects.get(ip=ip)
    nmap_proc = NmapProcess(targets=ip, options='-sV -p  '+ports)
    nmap_proc.run_background()

    while nmap_proc.is_running():
        result.rate = str(nmap_proc.progress)
        result.save()
        time.sleep(2)  # 两秒更新一次百分比
    result.rate = str(nmap_proc.progress)
    result.endtime = datetime.datetime.now()
    result.save()
    nm = nmap.PortScanner()
    nmrs = nm.analyse_nmap_xml_scan(nmap_proc.stdout)
    for port,v in nmrs['scan'][ip]['tcp'].items():
        scan_ip_info.objects.get_or_create(port=port,name=v['name'],state=v['state'],product=v['product']+'  '+v['version'],cpe=v['cpe'],ipfor_id=scanIP.objects.get(ip=ip).id)
Пример #16
0
def do_nmap_scan(targets, options=global_options):
    # 运行次数初始化
    trycnt = 0

    while True:
        # 运行时间初始化
        runtime = 0

        if trycnt >= retrycnt:
            print('-' * 50)
            return 'retry overflow'

        try:
            nmap_proc = NmapProcess(targets=targets,
                                    options=options,
                                    safe_mode=False)
            nmap_proc.run_background()

            while nmap_proc.is_running():
                if runtime >= timeout:  # 运行超时,结束掉任务,休息1分钟, 再重启这个nmap任务
                    print('-' * 50)
                    print("* timeout. terminate it...")
                    nmap_proc.stop()
                    # 休眠时间
                    sleep(5)
                    trycnt += 1
                    break
                else:
                    print('running[%ss]:%s' % (runtime, nmap_proc.command))
                    sleep(5)
                    runtime += 5
            if nmap_proc.is_successful():
                print('-' * 50)
                print(nmap_proc.summary)
                return nmap_proc.stdout

        except Exception as e:
            # raise e
            print(e)
            trycnt += 1
            if trycnt >= retrycnt:
                print('-' * 50)
                print('* retry overflow')
                return e
Пример #17
0
def nmap_scan(self, target: Dict[str, str]) -> None:
    """
    Nmap scan task. Handles one Nmap process to scan the provided host(s) or range(s).
    Updates the host database when finished; may push status updates if invoked from web context.
    :param target: Target hosts or ranges in a format suitable for Nmap.
    """
    storage.incr('scan_in_progress')
    options = Discovery.get_setting('scan_options')
    ports = Discovery.get_setting('ports')
    if ports:
        options += ' -p' + ports
    nm = NmapProcess(target['range'], options=options)
    nm.run_background()
    while nm.is_running():
        self.update_state(state="PROGRESS",
                          meta={
                              'progress': nm.progress,
                              'target': target['name']
                          })
        sleep(2)
    try:
        report = NmapParser.parse(nm.stdout)
    except NmapParserException as e:
        print(e)
    h = [(host.address, {
        str(p[0]): host.get_service(*p).get_dict()
        for p in host.get_open_ports()
    }) for host in report.hosts if host.is_up()]
    hosts = {
        host[0]: {
            'ports': host[1],
            'target': target['name']
        }
        for host in h
    }
    update_hosts(hosts)
    storage.set('last_nmap_scan', int(time()))
    if scan_in_progress() > 0:
        storage.decr('scan_in_progress')
    self.update_state(state="RESULTS",
                      meta={
                          'hosts': h,
                          'target': target['name']
                      })
Пример #18
0
 def scan_background(targets,options='-O -sV'):
     '''
     后台执行扫描,带进度输出
     :param targets:扫描的目标,可以是List集合对象也,可以是以逗号分隔的目标集合。如"baidu.com" ,["baidu.com","qq.com"] ,"baidu.com,qq.com"
     :param options:扫描参数,同namp一致。
     :return:成功返回扫描结果Dict对象,否则返回None
     '''
     try:
         nmapProcess=NmapProcess(targets=targets,options=options)
         nmapProcess.run_background()
         while nmapProcess.is_running():
             print("[*]Nmap Scan running: ETC: {0} DONE: {1}%".format(nmapProcess.etc,nmapProcess.progress))
             sleep(1)
         results=NmapParser.parse_fromstring(nmapProcess.stdout)
         jsonData=json.loads(json.dumps(results,cls=ReportEncoder))
         return jsonData
     except Exception as e:
         logging.error("Nmap scan error:{}".format(e))
         return None
Пример #19
0
def do_nmap_scan(targets, options=global_options):
	# 运行次数初始化
	trycnt = 0

	while True:
		# 运行时间初始化
		runtime = 0

		if trycnt >= retrycnt:
			print '-' * 50
			return 'retry overflow'

		try:
			nmap_proc = NmapProcess(targets=targets, options=options, safe_mode=False)
			nmap_proc.run_background()

			while nmap_proc.is_running():
				if runtime >= timeout:	# 运行超时,结束掉任务,休息1分钟, 再重启这个nmap任务
					print '-' * 50
					print "* timeout. terminate it..."
					nmap_proc.stop()
					# 休眠时间
					sleep(60)
					trycnt += 1
					break
				else:
					print 'running[%ss]:%s' % (runtime, nmap_proc.command)
					sleep(5)
					runtime += 5
			if nmap_proc.is_successful():
				print '-' * 50
				print nmap_proc.summary
				return nmap_proc.stdout

		except Exception, e:
			# raise e
			print e
			trycnt += 1
			if trycnt >= retrycnt:
				print '-' * 50
				print '* retry overflow'
				return e
Пример #20
0
def scan_host(target_host, num_tries):
    nm = NmapProcess(target_host, options='-sT -Pn -T3')
    cur_try = 0
    while cur_try < num_tries:
        logger.debug(
            "Now running scan attempt #%d for host at %s."
            % (cur_try + 1, target_host)
        )
        result = nm.run_background()
        while nm.is_running():
            logger.debug(
                "Scan running. ETC: %s. DONE: %s."
                % (nm.etc, nm.progress)
            )
            sleep(2)
        if nm.rc != 0:
            logger.warning(
                "Scan #%d for host at %s failed!"
                % (cur_try + 1, target_host)
            )
            cur_try += 1
        else:
            logger.debug(
                "Scan for host at %s succeeded!"
                % (target_host,)
            )
            break
    if str(nm.state) != str(nm.DONE):
        logger.warning(
            "Scan for host at %s failed!"
            % (target_host,)
        )
        return
    else:
        try:
            parsed = NmapParser.parse(nm.stdout)
        except NmapParserException as e:
            logger.error(
                "NmapParserException thrown: %s."
                % (e.msg,)
            )
        host = parsed.hosts[0]
        to_return = []
        for service in host.services:
            to_return.append(
                "%s//%s//%s//%s"
                % (
                    host.ipv4,
                    service.protocol,
                    str(service.port),
                    service.state
                )
            )
        return to_return
Пример #21
0
    def run(self):
        options = '-sT -sU -p{} -v -O'.format(','.join(self.ports))
        logger.debug('Ip scan options: {!r}, ip_ranges: {}'.format(
            options, self.ip_ranges))

        nmp_proc = NmapProcess(self.ip_ranges, options)
        nmp_proc.run_background()

        while nmp_proc.is_running():
            self.progress = float(nmp_proc.progress)
            log = {'progress': self.progress, 'log': ''}
            self._log(log)
            time.sleep(self.loop_time)

        if nmp_proc.rc == 0:
            stdout = nmp_proc.stdout
            self._result(stdout)
        else:
            sys.stderr.write(nmp_proc.stdout)
            sys.stderr.close()
            sys.exit(2)
Пример #22
0
    def update_ip(self):
        # hardcode it because I'm lazy AND it's a little tricky to discover from inside docker
        subnet = "192.168.7.0/24"
        nm = NmapProcess(subnet,
                         options="-T5 -n -p 8080 --open --min-parallelism 255")
        nm.run_background()

        while nm.is_running():
            sleep(0.5)
        nmap_report = NmapParser.parse(nm.stdout)
        for host in nmap_report.hosts:
            print(host.address)
            rv = requests.get(f"http://{host.address}:8080/api/v1/status")
            if rv.status_code == 200:
                if 'BackupBuffer' in rv.json():
                    print("Found device")
                    self.ip = host.address
                    return
        print("Unable to find any device")
        self.ip = None
        raise Exception("Unable to find device")
Пример #23
0
    def run_nmap_scan(self, targets, options, scan_id):
        print ('nmap targets: ' + str(targets) + ' nmap options: '+ str(options))
        nmap_proc = NmapProcess(targets=targets, options=options)
        nmap_proc.run_background()

        while nmap_proc.is_running():
            print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nmap_proc.etc, nmap_proc.progress))
            sleep(7)


        #Store in file
        file_path = "/root/Desktop/FinalYearProjectRESTAPI/automated_scans/reports/"+str(scan_id)+".xml"
        file = open(file_path, "w")
        data = nmap_proc.stdout
        file.write(data)
        file.close()

        print(data)
        print(type(data))

        return file_path
Пример #24
0
def do_scan(targets, options):
    parsed = None
    nmproc = NmapProcess(targets, options)
    nmproc.run_background()
    while nmproc.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
            nmproc.etc, nmproc.progress))
        time.sleep(2)

    rc = nmproc.rc
    if rc != 0:
        print("nmap scan failed: {0}".format(nmproc.stderr))
    print(type(nmproc.stdout))
    open('sasdsa', 'w').write(nmproc.stdout)

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

    return parsed
Пример #25
0
def do_nmap_scan(targets, options=NMAP_GLOBAL_OPTIONS):
    # 运行次数初始化
    trycnt = 0

    while True:
        # 运行时间初始化
        runtime = 0

        if trycnt >= NMAP_RETRYCNT:
            print "-" * 50
            return "retry overflow"

        try:
            nmap_proc = NmapProcess(targets=targets, options=options, safe_mode=False)
            nmap_proc.run_background()

            while nmap_proc.is_running():
                if runtime >= NMAP_TIMEOUT:  # 运行超时,结束掉任务,休息1分钟, 再重启这个nmap任务
                    print "-" * 50
                    print "* timeout. terminate it..."
                    nmap_proc.stop()
                    # 休眠时间
                    time.sleep(60)
                    trycnt += 1
                    break
                else:
                    print "running[%ss]:%s" % (runtime, nmap_proc.command)
                    time.sleep(5)
                    runtime += 5
            if nmap_proc.rc == 0:
                return nmap_proc.stdout

        except Exception, e:
            # raise e
            print e
            trycnt += 1
            if trycnt >= NMAP_RETRYCNT:
                print "-" * 50
                print "* retry overflow"
                return e
Пример #26
0
 def do_scan(self):
     """
     对targets进行扫描,并返回探测结果
     :param targets: 扫描目标
     :param options: 扫描选项
     :return:
     """
     nmproc = NmapProcess(self.ip, self.options)
     nmproc.run_background()  # 在后台运行
     while nmproc.is_running():
         nmaptask = nmproc.current_task
         if nmaptask:
             print("Task {0} ({1}): ETC: {2} DONE: {3}%".format(
                 nmaptask.name, nmaptask.status, nmaptask.etc,
                 nmaptask.progress))
         sleep(2)
     self.raw_data = nmproc.stdout  # 原始扫描数据
     try:
         self.parsed = NmapParser.parse(nmproc.stdout)  # 解析扫描的数据
     except NmapParserException as e:
         print("Exception raised while parsing scan: {0}".format(e.msg))
         return
Пример #27
0
def nmap_service_scan(host, service, command):
    port = service.port
    nm = NmapProcess(host.address, options=command + " -p " + str(port))
    # change to sudo_run(run_as='root') to run syn scans
    nm.run_background()
    command = nm.get_command_line()
    print(command)
    while nm.is_running():
        print("Nmap Service Scan running:" + host.address + " : " +
              str(service.port) +
              " ETC: {0} DONE: {1}%".format(nm.etc, nm.progress))
        sleep(10)
    nmap_report = NmapParser.parse(nm.stdout)
    for host_service in nmap_report.hosts:
        for serv in host_service.services:
            pserv = "{0:>5s}/{1:3s}  {2:12s}  {3} ".format(
                str(serv.port), host.address, serv.protocol, serv.state,
                serv.service)
            print(pserv)
            for result in serv.scripts_results:
                print(result["output"])
            print("\n")
Пример #28
0
    def run_nmscan(pid: int):
        """
        When run, queries the process information by the id provided from the database.
        Runs the test and returns the ouput of the test to the database
        :param pid: Id of process to run
        :return: None
        """
        process = Process.query.filter_by(id=pid).first()
        scan = Scan.query.filter_by(id=process.scan_id).first()
        target_obj = Target.query.filter_by(id=scan.target_id).first()
        target = target_obj.domain
        nm = NmapProcess(targets=target, options="-sV -Pn -f --mtu 64 -p '*' -O")
        rc = nm.run_background()
        process.status = nm.state
        process.progress = nm.progress
        process.date_started = datetime.now().isoformat()
        scan.date_started = datetime.now().isoformat()
        db.session.commit()

        if nm.has_failed():
            process.output = "nmap scan failed: {0}".format(nm.stderr)
            db.session.commit()
            return 1

        while nm.is_running():
            print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nm.etc,
                                                                  nm.progress))
            if int(scan.progress) < int(float(nm.progress)):
                process.progress = int(float(nm.progress))
                scan.progress = int(float(nm.progress))
                db.session.commit()
            sleep(5)

        process.date_completed = datetime.now().isoformat()
        scan.date_completed = datetime.now().isoformat()
        if nm.has_failed():
            process.status = nm.state
            scan.status = nm.state
            process.output = str(nm.stderr)
        elif nm.is_successful():
            process.status = 3
            scan.status = 3
            scan.progress = 100
            nmap_full_output = json.dumps(cb.data(fromstring(str(nm.stdout))))
            nmap_output = Nmap.parse_nmap_output(nmap_full_output)
            if nmap_output:
                process.output = json.dumps(nmap_output)
                scan.output = json.dumps(nmap_output)
            else:
                scan.output = None
        db.session.commit()
Пример #29
0
def do_scan(targets, options):
    parsed = None
    nmap_proc = NmapProcess(targets, options)
    print("Starting scanning with Nmap ( http://nmap.org )")
    nmap_proc.run_background()
    while nmap_proc.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
            datetime.datetime.fromtimestamp(float(
                nmap_proc.etc)).strftime('%Y-%m-%d %H:%M:%S'),
            nmap_proc.progress))
        sleep(5)
#print("#####################")

    if nmap_proc.rc != 0:
        print("nmap scan failed: {0}".format(nmap_proc.stderr))
    #print (type(nmap_proc.stdout))

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

    return parsed, nmap_proc.stdout
Пример #30
0
class ScanEngine(object):
    def __init__(self,config):
        self.engine = NmapProcess(config.targets, config.options)

    def run(self):
        """Execute scan"""
        syslog.syslog("Starting scan")
        self.engine.run_background()
        while self.engine.is_running():
            time.sleep(15)
            print "Scan is %s percent complete" % self.engine.progress
        syslog.syslog("Completed scan")
    
    def process(self):
        """parse and pre-process scan results"""
        
        try:
            self.parsed = NmapParser.parse(self.engine.stdout)
            syslog.syslog("Processing output")
        except Exception as e:
            syslog.syslog("Failed to parse output"+e)

        for h in self.parsed.hosts:
            print h.address
Пример #31
0
def do_scan(targets, options):
    parsed = None
    nmproc = NmapProcess(targets, options)
    #rc = nmproc.run()
    rc = nmproc.run_background()
    while nmproc.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nmproc.etc,nmproc.progress))
        sleep(2)
    #print(type(nmproc.stdout))
    file = open(output_name+'.xml','w')
    file.write(nmproc.stdout)
    file.close()
    try:
        parsed = NmapParser.parse(nmproc.stdout)
    except NmapParserException as e:
        print("Exception raised while parsing scan: {0}".format(e.msg))

    return parsed
Пример #32
0
def do_scan(targets, options):
    parsed = None
    nmproc = NmapProcess(targets, options)
    rc = nmproc.run_background()
    while nmproc.is_running():
        print("Nmap Scan is running: ETC: {0} DONE: {1}%".format(nmproc.etc, nmproc.progress))
        sleep(2)
    print("rc: {0} output: {1}".format(nmproc.rc, nmproc.summary))

    if rc != 0:
        print("nmap scan failed: {0}".format(nmproc.stderr))
    print(type(nmproc.stdout))

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

    return parsed
Пример #33
0
def do_scan(targets, options):
    parsed = None
    nmproc = NmapProcess(targets, options)
    rc = nmproc.run_background()
    while nmproc.is_running():
        print("Nmap Scan is running: ETC: {0} DONE: {1}%".format(
            nmproc.etc, nmproc.progress))
        sleep(2)
    print("rc: {0} output: {1}".format(nmproc.rc, nmproc.summary))

    if rc != 0:
        print("nmap scan failed: {0}".format(nmproc.stderr))
    print(type(nmproc.stdout))

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

    return parsed
Пример #34
0
#!/usr/bin/env python

from libnmap.process import NmapProcess
from time import sleep


nmap_proc = NmapProcess(targets="scanme.nmap.org", options="-sT")
nmap_proc.run_background()
while nmap_proc.is_running():
    nmaptask = nmap_proc.current_task
    if nmaptask:
        print "Task {0} ({1}): ETC: {2} DONE: {3}%".format(nmaptask.name,
                                                           nmaptask.status,  
                                                           nmaptask.etc,
                                                           nmaptask.progress)
    sleep(0.5)

print "rc: {0} output: {1}".format(nmap_proc.rc, nmap_proc.summary)
print nmap_proc.stdout
Пример #35
0
def scan():
    ttype = input(
        "Please select the type of target to scan: \n 1. Manually Enter Target(s) \n 2. Select File Containing Targets (The file should be new line or comma seperated) \n > "
    )
    if ttype == '1':  # When a Single target is to be scanned
        targ = input(
            "Please enter your target to scan: (Ex: mysite.com or 192.168.1.1, scanme.nmap.org or 192.168.1.*) \n > "
        )
        nswitch = input(
            "\n Please select nmap switches you wish to use: (Ex: -sV -Pn -A) \n > "
        )
        if targ != '':
            try:
                nmap_proc = NmapProcess(targets=targ, options=nswitch)
                nmap_proc.run_background()
            except PermissionError:
                print(
                    "Please make sure Nmap is installed and/or is accessible \n"
                )
                input("Press Enter to exit.")
                exit()
            while nmap_proc.is_running():
                print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
                    nmap_proc.etc, nmap_proc.progress))
                sleep(
                    10
                )  # Adjust this value in order to change how frequently the progress output is printed on terminal.
            print("rc: {0} output: {1}".format(nmap_proc.rc,
                                               nmap_proc.summary))
            print(nmap_proc.stderr)
            return nmap_proc.stdout
        else:
            print("Please select correct value \n")
            redo = scan()
    # Triggered when multiple targets are to be slected
    elif ttype == '2':
        floc = input("Input File Path (Press Enter Key to browse your PC): ")
        if floc == '':
            tkwindow = tkinter.Tk()
            tkwindow.withdraw()  # Used to Hide the tkinter window.
            filename = filedialog.askopenfilename(
                initialdir="/",
                title="Select Your File",
                filetypes=(("Txt Files", "*.txt"), ("All Files", "*.*")))
            print("The File you selected is: " + filename)
            targets = targ_to_list(filename)
            nswitch = input(
                "\n Please select nmap switches you wish to use: \n > ")
            try:
                nmap_proc = NmapProcess(targets=targets, options=nswitch)
                nmap_proc.run_background()
            except PermissionError:
                print("Please make sure Nmap is installed and/or accessible.")
                input("Press Enter to exit.")
                exit()
            while nmap_proc.is_running():
                print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
                    nmap_proc.etc, nmap_proc.progress))
                sleep(
                    10
                )  # Adjust this value in order to change how frequently the progress output is printed on terminal.
            print("rc: {0} output: {1}".format(nmap_proc.rc,
                                               nmap_proc.summary))
            print(nmap_proc.stderr)
            return nmap_proc.stdout
        else:
            print(floc)
    else:
        print("Please select a correct option!")
        redo = scan()
Пример #36
0
# -*- coding: utf-8 -*-

from libnmap.process import NmapProcess
from libnmap.parser import NmapParser
from time import sleep
import sys
import socket

if len(sys.argv) >= 2:
    mac = sys.argv[1]
    try:
        ip = sys.argv[2]
    except:
        ip = socket.gethostbyname(socket.gethostname()) #local ip
else:
    print("Insert MAC Address to search")
    sys.exit(0)

nm = NmapProcess(ip+"/24",options="-sP")
nm.run_background()

while nm.is_running():
    print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nm.etc,nm.progress))
    sleep(2)
nmap_report = NmapParser.parse(nm.stdout)
res = list(filter(lambda n:n.mac == mac.strip().upper(), filter(lambda host:host.is_up(), nmap_report.hosts)))
if res ==[]:
    print("Host is down or Mac address not exist")
else:
    print("MAC: {} with IP {}".format(mac, res[0].address))
Пример #37
0
class NmapAdapter(ToolAdapter):
    @log(logger)
    def __init__(self, ip, commandline=None):
        if self.is_valid_ip(ip):
            self.ip = ip
        else:
            raise ValueError

        if commandline:
            self.commandline = commandline
        else:
            self.commandline = '-sV'
        self.nmproc = NmapProcess(self.ip, self.commandline)

    @log(logger)
    def start(self):
        logger.info('nmap started on IP {}'.format(self.ip))
        rc = self.nmproc.run_background()
        if self.nmproc.stderr:
            logger.critical('nmap has failed: {0}'.format(self.nmproc.stderr))
            print('nmap scan has failed:', self.nmproc.stderr)

    def status(self):
        if self.nmproc.is_running():
            return 'running: {0}%'.format(self.nmproc.progress)
        else:
            if self.nmproc.has_failed():
                return 'failed'
            elif self.nmproc.is_successful():
                return 'finished (successfully)'
            else:
                return 'stopped'

    @log(logger)
    def stop(self):
        if self.nmproc.is_running():
            self.nmproc.stop()

    @log(logger)
    def get_result_json(self):
        report = None
        try:
            report = NmapParser.parse(self.nmproc.stdout)
        except NmapParserException as e:
            logger.critical("Exception raised while parsing scan: {0}".format(
                e.msg))
            print("Exception raised while parsing scan: {0}".format(e.msg))
            return None
        report_dict = {}
        report_dict['starttime'] = report.started
        report_dict['endtime'] = report.endtime
        report_dict['host'] = self.ip
        host = report.hosts[0]
        report_dict['hoststatus'] = host.status
        services = []
        for serv in host.services:
            service = {}
            service['port'] = serv.port
            service['protocol'] = serv.protocol
            service['state'] = serv.state
            service['service'] = serv.service
            if len(serv.banner):
                service['banner'] = serv.banner
            if len(serv.cpelist):
                cpe = {}
                cpe['part'] = serv.cpelist[0].get_part()
                cpe['vendor'] = serv.cpelist[0].get_vendor()
                cpe['product'] = serv.cpelist[0].get_product()
                cpe['version'] = serv.cpelist[0].get_version()
                cpe['update'] = serv.cpelist[0].get_update()
                cpe['edition'] = serv.cpelist[0].get_edition()
                cpe['language'] = serv.cpelist[0].get_language()
                service['cpe'] = cpe
            services.append(service)
        report_dict['services'] = services
        json_data = dumps(report_dict)
        return json_data
Пример #38
0
tweetComm = getLastTweet()

label, command, IPcode = tweetComm.split("|", 3)

IPaddr = decodeIP(IPcode)

#flood IP with pings - basic DoS
if command == "ds7656":
    print "ping " + IPaddr
    os.system("ping -c 10 " + IPaddr)
#add client to list
elif command == "ac73456":
    print "add client " + IPaddr
    file = open("clientList.txt", "a")
    file.write(IPaddr)
    file.close()
#scan IP
elif command == "sc26769":
    print "scan " + IPaddr
    nmap_proc = NmapProcess(targets="scanme.nmap.org", options="-sT")
    nmap_proc.run_background()
    while nmap_proc.is_running():
        print("Nmap Scan running: ETC: {0} DONE: {1}%".format(
            nmap_proc.etc, nmap_proc.progress))
        sleep(2)
    print("rc: {0} output: {1}".format(nmap_proc.rc, nmap_proc.summary))

else:
    print "No valid command found"
Пример #39
0
class NmapScan(BaseScanner):
    '''
    Nmap scanning class, perform a couple of nmap scans of varying intensity on the specified target and reports this back in the form of ServiceResults and a SystemResult
    '''

    def __init__(self, ip, directory):
        '''
        set params, config, etc
        '''
        super(self.__class__, self).__init__(ip.strip())
        
        if(directory.endswith("/")):
            outputfile = directory + ip + "."
        else:
            outputfile = directory + "/" + ip + "."
        self.FileBase = outputfile
        c = AlxConfiguration()
        self.currentScan = None
        self.interval = 5
        self.timer = None
        self.running= False
        self.hasQuit = False
        q = Queue()
        q.put(c.getQuickScanOpts())
        q.put(c.getIntermediateScanOpts())
        q.put(c.getUdpScanOpts())
        q.put(c.getFullScanOpts())
        
        self.scanQueue = q
        
    
    def Execute(self):
        #Start nmap in different thread
        if not self.running:
            self.timer = threading.Timer(self.interval, self._run)
            self.timer.start()
            self.running = True
 
    def Quit(self):
        #print("Quitting scan against {0}...").format(self.getIP())
        self.timer.cancel()
        self.running = False
        self.timer = None
        self.hasQuit = True
    
    def _run(self):
        if(self.running):
            self.running = False
            self.runNmap()
            if(not self.hasQuit):
                self.Execute()
    
    def runNmap(self):
        #gets executed every x seconds
        #check current nmap scan -> if finished then parse results and start new one, otherwise wait and report status
        
        if not self.currentScan:
            #create new scan
            self.createNewScan()
        else:
            #report current scan status
            if(self.currentScan.is_running()):
                print("Nmap scan for {0} ({2}) progress: {1}%").format(self.getIP(), self.currentScan.progress, self.currentScan.options)
                pass
            else:
                if(self.currentScan.is_successful()):
                    self.ParseResults(self.currentScan)
                    self.currentScan = None
                self.createNewScan()
            pass
        
        
    def createNewScan(self):
        if self.scanQueue and not self.scanQueue.empty():
            opt = self.scanQueue.get()
            ip = self.getIP()
            self.currentScan = NmapProcess(targets=ip, options=opt, safe_mode=False)
            self.currentScan.run_background()
        else:
            self.Quit()
    
    def ParseResults(self, nmapscan):
        nmap_report = NmapParser.parse(nmapscan.stdout)
        hresults = []
        for h in nmap_report.hosts:
            #assemble host
            #address, os, distance, fingerprint, status
            print("Assembling host data {0} {1} {2} {3} {4}".format(h.address, h.os_fingerprint, h.distance, h.status, h.mac))
            hres = SystemResult.SystemResult(h.address,h.os_fingerprint, h.distance, h.status, h.mac)
            hresults.append(hres)
            for s in h.services:
                #add services to host
                if(s.state == "open"):
                    serv = ServiceResult.ServiceResult(s.port, s.protocol, s.reason, s.service,  s.state, s.banner)
                    hres.addService(serv)
                    print("Found service {0} {1} {2} {3}").format(s.service, s.protocol, s.state, s.banner)
                    self.UpdateListeners(hresults)