1

我的目标是在 ElastAlert 中针对这种情况发出警报:午夜到凌晨 2 点之间没有发生任何事件。(适用于任何日期)。问题是如何对 Elasticsearch 进行查询以匹配除特定时间之外的任何日期,因为您不能在“日期”类型的时间戳上使用正则表达式或通配符。有什么建议么?

此代码返回“解析失败”:

"range": {
  "timestamp": {
    "gte": "20[0-9]{2}-[0-9]{2}-[0-9]{2}T00:00:00.000Z",
    "lt": "20[0-9]{2}-[0-9]{2}-[0-9]{2}T02:00:00.000Z"
  }
}
4

2 回答 2

0

我无权编写自定义规则,所以我的解决方案是在 logstash 中进行更改。添加了字段 hour_of_day,其中的值来自时间戳。因此,我们可以使用如下过滤器创建扁平化规则:

filter:
 - query:
      query_string:
        query: "hour_of_day: 0 OR hour_of_day: 1"
于 2018-07-30T13:51:46.903 回答
0

在自定义规则中处理它是理想的。

我编写了以下代码来执行相同类型的过滤: 注意,使用的依赖项(dateutil、elastalert.utils)已经与 elastalert 框架捆绑在一起。

import dateutil.parser

from ruletypes import RuleType

# elastalert.util includes useful utility functions
# such as converting from timestamp to datetime obj
from util import ts_to_dt

# Modified version of http://elastalert.readthedocs.io/en/latest/recipes/adding_rules.html#tutorial
# to catch events happening outside a certain time range
class OutOfTimeRangeRule(RuleType):
    """ Match if input time is outside the given range """

    # Time range specified by including the following properties in the rule:
    required_options = set(['time_start', 'time_end'])

    # add_data will be called each time Elasticsearch is queried.
    # data is a list of documents from Elasticsearch, sorted by timestamp,
    # including all the fields that the config specifies with "include"
    def add_data(self, data):
        for document in data:
            # Convert the timestamp to a time object
            login_time = document['@timestamp'].time()

            # Convert time_start and time_end to time objects
            time_start = dateutil.parser.parse(self.rules['time_start']).time()
            time_end = dateutil.parser.parse(self.rules['time_end']).time()

            # If time is outside office hours
            if login_time < time_start or login_time > time_end:

                # To add a match, use self.add_match
                self.add_match(document)

    # The results of get_match_str will appear in the alert text
    def get_match_str(self, match):
        return "logged in outside %s and %s" % (self.rules['time_start'], self.rules['time_end'])

    def garbage_collect(self, timestamp):
        pass
于 2018-07-05T18:04:25.690 回答