# Path: server/es.py
# class Es():
#     def __init__(self):
#         USERNAME = ElasticConfig.USERNAME
#         PASSWORD = ElasticConfig.PASSWORD
#         HOST = ElasticConfig.HOST
#         PORT = ElasticConfig.PORT
#         if USERNAME == "" and PASSWORD == "":
#             CONN = "http://"+HOST+":"+PORT
#         else:
#             CONN = "http://"+USERNAME+":"+PASSWORD+"@"+HOST+":"+PORT
#         self.es = Elasticsearch([CONN])
#         self.confIndex = ElasticConfig.INDEX_CONFIG["index"]
#         self.confType = ElasticConfig.INDEX_CONFIG["type"]
#         self.assetIndex = ElasticConfig.INDEX_ASSETS["index"]
#         self.assetType = ElasticConfig.INDEX_ASSETS["type"]
# 
#     def init_scan_config(self):
#         doc = SCANCONFIG
#         if self.es.exists(index=self.confIndex, doc_type=self.confType, id="1"):
#             self.es.delete(index=self.confIndex, doc_type=self.confType, id="1")
#         self.es.create(index=self.confIndex, doc_type=self.confType, id="1", body=doc)
# 
#     def get_scan_config(self):
#         config = self.es.search(index=self.confIndex, doc_type=self.confType, body={
#         "query":{
#             "term" : { "_id" : "1" }
#         }
#     }, request_timeout=5)["hits"]["hits"]
#         if len(config) == 0:
#             return False
#         else:
#             return config[0]["_source"]
# 
#     def update_scan_config(self, name, value):
#         self.es.update(index=self.confIndex, doc_type=self.confType, id="1", body={
#             "doc":{
#                 name: value.strip()
#             }    
#         })
#         return True
# 
#     #vulscan 
#     def init_plugins(self):
#         if self.es.indices.exists(ElasticConfig.INDEX_VULTASKS["index"]):
#             self.es.indices.delete(ElasticConfig.INDEX_VULTASKS["index"])
#         self.es.indices.create(ElasticConfig.INDEX_VULTASKS["index"])
# 
#     #vulscan
#     def get_plugins_doc(self, name, value):
#         v = self.es.search(index=ElasticConfig.INDEX_VULTASKS["index"], doc_type=ElasticConfig.INDEX_VULTASKS["type"], body={
#             "query":{"term" : {  name : value}}
#             }, request_timeout=5)["hits"]["hits"]
#         
#         if len(v) == 0:
#             return False
#         else:
#             return v[0]["_source"]
# 
#     #vulscan
#     def insert_plugins_doc(self, doc):
#         self.es.index(index=ElasticConfig.INDEX_VULTASKS["index"], doc_type=ElasticConfig.INDEX_VULTASKS["type"], body=doc)
#         return True
# 
#     #return data <type 'generator'>
#     def get_all_plugins(self):
#         index = ElasticConfig.INDEX_VULTASKS["index"]
#         doc_type = ElasticConfig.INDEX_VULTASKS["type"]
#         scroll = "2m"
#         size = 30
#         body = {"query" : {"match_all": {}}}
#         data = helpers.scan(client=self.es, query=body, index=index, doc_type=doc_type, scroll=scroll, size=size)
#         return data
# 
#     #search assets
#     def get_assets_doc(self, searchGroup):
#         index = self.assetIndex
#         doc_type = self.assetType
#         scroll = "5m"
#         size = 100
#         body = {"query":{"bool": {"must": searchGroup}}}
#         data = helpers.scan(client=self.es, query=body, index=index, doc_type=doc_type, scroll=scroll, size=size)
#         return data
# 
# Path: celerynode/api.py
# def api_hostScan(hostsList, ports, arguments='-Pn -sV', queue="master"):
#     """
#     hosts: 192.168.1.1-192.168.1.128,192.168.1.129-192.168.1.130
#     arguments: -Pn -sV
#     """
#     hostsList = hostsList.split(",")
#     for hostsQ in hostsList:
#         if hostsQ.find("|") != -1:
#             hosts, queue = hostsQ.split("|")
#         else:
#             hosts, queue = (hostsQ, "master")
#         ipList = get_ip_list(hosts)
#         for v in ipList:
#             hostScan.apply_async(args=[v, ports, arguments, queue], queue=queue)
#     return True


import sys
import os
import time
import thread
from verify import portCheck
from server.es import Es
from celerynode.api import api_hostScan
#coding:utf8

sys.path.append(os.path.split(os.path.realpath(__file__))[0]+"/../../")

if __name__ == "__main__":
    es = Es()  
    thread.start_new_thread(portCheck,(es, "test")) 
    try:
        ac_data = []
        while True:
            now_time = time.localtime()
            now_hour = now_time.tm_hour
            now_day = now_time.tm_mday
            now_date = str(now_time.tm_year) + str(now_time.tm_mon) + str(now_day)
            cy_day, ac_hour = es.get_scan_config()["scanPeriod"].split('|') #读取周期配置
            if now_hour == int(ac_hour) and now_day % int(cy_day) == 0 and now_date not in ac_data:
                ac_data.append(now_date)
                scanHosts = es.get_scan_config()["scanHosts"]
                scanPorts = es.get_scan_config()["scanPorts"]
                print (scanHosts, scanPorts)

# Path: server/es.py
# class Es():
#     def __init__(self):
#         USERNAME = ElasticConfig.USERNAME
#         PASSWORD = ElasticConfig.PASSWORD
#         HOST = ElasticConfig.HOST
#         PORT = ElasticConfig.PORT
#         if USERNAME == "" and PASSWORD == "":
#             CONN = "http://"+HOST+":"+PORT
#         else:
#             CONN = "http://"+USERNAME+":"+PASSWORD+"@"+HOST+":"+PORT
#         self.es = Elasticsearch([CONN])
#         self.confIndex = ElasticConfig.INDEX_CONFIG["index"]
#         self.confType = ElasticConfig.INDEX_CONFIG["type"]
#         self.assetIndex = ElasticConfig.INDEX_ASSETS["index"]
#         self.assetType = ElasticConfig.INDEX_ASSETS["type"]
# 
#     def init_scan_config(self):
#         doc = SCANCONFIG
#         if self.es.exists(index=self.confIndex, doc_type=self.confType, id="1"):
#             self.es.delete(index=self.confIndex, doc_type=self.confType, id="1")
#         self.es.create(index=self.confIndex, doc_type=self.confType, id="1", body=doc)
# 
#     def get_scan_config(self):
#         config = self.es.search(index=self.confIndex, doc_type=self.confType, body={
#         "query":{
#             "term" : { "_id" : "1" }
#         }
#     }, request_timeout=5)["hits"]["hits"]
#         if len(config) == 0:
#             return False
#         else:
#             return config[0]["_source"]
# 
#     def update_scan_config(self, name, value):
#         self.es.update(index=self.confIndex, doc_type=self.confType, id="1", body={
#             "doc":{
#                 name: value.strip()
#             }    
#         })
#         return True
# 
#     #vulscan 
#     def init_plugins(self):
#         if self.es.indices.exists(ElasticConfig.INDEX_VULTASKS["index"]):
#             self.es.indices.delete(ElasticConfig.INDEX_VULTASKS["index"])
#         self.es.indices.create(ElasticConfig.INDEX_VULTASKS["index"])
# 
#     #vulscan
#     def get_plugins_doc(self, name, value):
#         v = self.es.search(index=ElasticConfig.INDEX_VULTASKS["index"], doc_type=ElasticConfig.INDEX_VULTASKS["type"], body={
#             "query":{"term" : {  name : value}}
#             }, request_timeout=5)["hits"]["hits"]
#         
#         if len(v) == 0:
#             return False
#         else:
#             return v[0]["_source"]
# 
#     #vulscan
#     def insert_plugins_doc(self, doc):
#         self.es.index(index=ElasticConfig.INDEX_VULTASKS["index"], doc_type=ElasticConfig.INDEX_VULTASKS["type"], body=doc)
#         return True
# 
#     #return data <type 'generator'>
#     def get_all_plugins(self):
#         index = ElasticConfig.INDEX_VULTASKS["index"]
#         doc_type = ElasticConfig.INDEX_VULTASKS["type"]
#         scroll = "2m"
#         size = 30
#         body = {"query" : {"match_all": {}}}
#         data = helpers.scan(client=self.es, query=body, index=index, doc_type=doc_type, scroll=scroll, size=size)
#         return data
# 
#     #search assets
#     def get_assets_doc(self, searchGroup):
#         index = self.assetIndex
#         doc_type = self.assetType
#         scroll = "5m"
#         size = 100
#         body = {"query":{"bool": {"must": searchGroup}}}
#         data = helpers.scan(client=self.es, query=body, index=index, doc_type=doc_type, scroll=scroll, size=size)
#         return data
# 
# Path: celerynode/api.py
# def api_hostScan(hostsList, ports, arguments='-Pn -sV', queue="master"):
#     """
#     hosts: 192.168.1.1-192.168.1.128,192.168.1.129-192.168.1.130
#     arguments: -Pn -sV
#     """
#     hostsList = hostsList.split(",")
#     for hostsQ in hostsList:
#         if hostsQ.find("|") != -1:
#             hosts, queue = hostsQ.split("|")
#         else:
#             hosts, queue = (hostsQ, "master")
#         ipList = get_ip_list(hosts)
#         for v in ipList:
#             hostScan.apply_async(args=[v, ports, arguments, queue], queue=queue)
#     return True


# Path: server/monitor/index.py
import sys
import os
import time
import thread
from verify import portCheck
from server.es import Es
from celerynode.api import api_hostScan

#coding:utf8

sys.path.append(os.path.split(os.path.realpath(__file__))[0]+"/../../")

if __name__ == "__main__":
    es = Es()  
    thread.start_new_thread(portCheck,(es, "test")) 
    try:
        ac_data = []
        while True:
            now_time = time.localtime()
            now_hour = now_time.tm_hour
            now_day = now_time.tm_mday
            now_date = str(now_time.tm_year) + str(now_time.tm_mon) + str(now_day)
            cy_day, ac_hour = es.get_scan_config()["scanPeriod"].split('|') #读取周期配置
            if now_hour == int(ac_hour) and now_day % int(cy_day) == 0 and now_date not in ac_data:
                ac_data.append(now_date)
                scanHosts = es.get_scan_config()["scanHosts"]
                scanPorts = es.get_scan_config()["scanPorts"]
                print (scanHosts, scanPorts)

                api_hostScan(hostsList=scanHosts, ports=scanPorts)