From 508bab867f52e944c7dce01f5f771143d738870c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ernesto=20Canales=20Pere=C3=B1a?= Date: Sun, 3 Sep 2023 23:06:38 +0200 Subject: [PATCH] Upload Server --- server.py | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 server.py diff --git a/server.py b/server.py new file mode 100644 index 0000000..433a8a0 --- /dev/null +++ b/server.py @@ -0,0 +1,74 @@ + +import tornado.ioloop +import tornado.httpclient +import tornado.web +import json +import joblib +import sys + +import pandas as pd + +arguments = sys.argv +lib = arguments[1] +model = joblib.load('./models/' + lib) +head_names=["received_bytes","send_bytes","port_duration","total_duration","jitter","differents_port"] + + + +class GenericHandler(tornado.web.RequestHandler): + + TelegramBot="" + ChatTelegramId="" + message = "Alerta por escaneo. Puertos UDP escaneados desde la IP: " + + def send_telegram(self,ip): + + url = f"https://api.telegram.org/bot{self.TelegramBot}/sendMessage" + data = {"chat_id": self.ChatTelegramId, "text": self.message + ip} + headers = {"Content-Type": "application/json"} + body = json.dumps(data) + + http_client = tornado.httpclient.AsyncHTTPClient() + try: + response = http_client.fetch( + url, + method="POST", + body=body, + headers=headers, + ) + except: + pass + finally: + http_client.close() + + def post(self): + + plain_text = self.request.body.decode('utf-8') + metrics = plain_text.split("||")[0] + ip_src = plain_text.split("||")[1] + + check_data = list(map(lambda x: float(x), metrics.split(','))) + df_predict = pd.DataFrame([check_data]) + df_predict.columns = head_names + pre = model.predict(df_predict) + result = pre[0] + self.set_header("Content-Type", "text/plain") + self.write(str(result)) + if round(result) == 1: + self.send_telegram(ip_src) + self.finish() + + +def make_app(): + return tornado.web.Application([ + (r"/check", GenericHandler), + ]) + + +def main(): + app = make_app() + app.listen(8888) + tornado.ioloop.IOLoop.current().start() + +if __name__ == "__main__": + main()