一个使用Python加密连接Elasticsearch的简单封装

依赖:

elasticsearch==7.17.9

eshelpercore.py:

#!/usr/bin/python3
# coding=utf-8
import datetime
import os
import ssl

from elasticsearch import Elasticsearch


def get_env() -> str:
    # 这里指定查询的环境索引
    return "uat"


def get_output_file_path(filename) -> str:
    return "/etc/zabbix/zabbix_agentd.d/" + filename


class ElasticObj:
    def __init__(self):
        os.environ['ELASTIC_CLIENT_APIVERSIONING'] = "true"
        ssl_context = ssl.create_default_context(cafile="./elasticsearch-ca.pem")
        ssl_context.check_hostname = False

        self.es = Elasticsearch(hosts=["127.0.0.1"],

                                http_auth=('username', 'password'),
                                port=9200,
                                ssl_context=ssl_context,
                                scheme="https",
                                # use_ssl=True, verify_certs=True,
                                )

    def get_by_query(self, query, fetch_size=None):
        body = {'query': query}
        if fetch_size is not None:
            body['fetch_size'] = fetch_size
        return self.es.sql.query(body=body)

    def get_by_cursor(self, cursor: str):
        return self.es.sql.query(body={"cursor": cursor})

    def get_by_body(self, index, body):
        return self.es.search(index=index, body=body)


def get_select_list_by_stamp(begin, end):  # 秒时间戳
    from_obj = datetime.datetime.fromtimestamp(begin)
    to_obj = datetime.datetime.fromtimestamp(end)
    select_list = []
    days = (to_obj - from_obj).days
    if days == 0:
        select_list = [to_obj.strftime("%Y-%m-%d")]
    else:
        while days >= 0:
            from_str = from_obj.strftime("%Y-%m-%d")
            select_list.append(from_str)
            days -= 1
            from_obj = from_obj + datetime.timedelta(days=1)
    return select_list


def get_dir() -> str:
    return os.path.dirname(os.path.abspath(__file__))

 

posted @ 2024-05-21 22:48  Jackie_JK  阅读(67)  评论(0编辑  收藏  举报