def run(self): while True: try: ack_key = redis.get_key("ack_scan_*") if len(ack_key): timeout_data = redis.zrangebyscore(ack_key[0], "-INF", time() - 60 * 5, 0, 1) if timeout_data: log.debug("触发ack:%s" % timeout_data[0]) redis.zrem(ack_key[0], timeout_data[0]) redis.put(ack_key[0].replace("ack_scan_", "scan_"), timeout_data[0]) scan_key = redis.get_key("scan_*") if len(scan_key): scanning_num = load_setting().get("scanning_num", 5) if len(multiprocessing.active_children()) < scanning_num: log.debug("【nmap】指定最大并发进程数%s,当前空闲进程数:%s,当前nmap待检测任务数:%s" % ( scanning_num, scanning_num - len(multiprocessing.active_children()), redis.qsize(scan_key[0]))) log.debug("子进程数目:%s" % len(multiprocessing.active_children())) scan_data = redis.get(scan_key[0]) p = ChildProcess(scan_key[0], scan_data) p.start() else: sleep(1) else: sleep(1) break except Exception as e: log.exception(e) sleep(60 * 5)
def run_nmap(scan_key, scan_data): try: redis.zadd("ack_" + scan_key, {scan_data: time()}) nm = Nmap() scan_data_dict = str2dict(scan_data) ip = scan_data_dict['ip'] port = str(scan_data_dict['port']) log.info("pid=%s,nmap开始扫描:%s" % (os.getpid(), scan_data)) timeout = int(globals().get("SCAN_TIMEOUT", 300)) if FIND_HOST: nm.scan(hosts=ip, arguments='-sV -p%s -T4 --version-intensity 4' % port, timeout=timeout) else: nm.scan(hosts=ip, arguments='-sV -PS445,22 -p%s -T4 --version-intensity 4' % port, timeout=timeout) nmap_result_list = nm.scan_result() if nmap_result_list: mongo = Mongodb(host=MONGO_IP, port=MONGO_PORT, username=MONGO_USER, password=MONGO_PWD) mongo_scan_result = mongo.conn[MONGO_DB_NAME][ MONGO_RESULT_COLL_NAME] for nmap_result in nmap_result_list: nmap_result['port_status'] = 'open' nmap_result['base_task_id'] = ObjectId( scan_data_dict['base_task_id']) nmap_result['create_time'] = datetime.datetime.now().strftime( '%Y-%m-%d') nmap_result['ip_port'] = "%s:%s" % (nmap_result['ip'], str(nmap_result['port'])) if VULSCAN_KEY: redis.sadd( VULSCAN_KEY, json.dumps({ "protocol": nmap_result["service"], "info_id": 0, "finger": nmap_result["version_info"], "type": "portscan", "port": nmap_result["port"], "url": nmap_result["ip"] })) mongo_scan_result.insert_many(nmap_result_list, ordered=False) mongo.conn.close() redis.zrem("ack_" + scan_key, scan_data) except KeyboardInterrupt as e: log.exception(scan_data) except Exception as e: log.exception(scan_data) redis.zrem("ack_" + scan_key, scan_data)