Skip to content

Commit de8d827

Browse files
authored
Create check_query.py
1 parent 7fa1e20 commit de8d827

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

check_query.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
from elasticsearch import Elasticsearch ## ES SDK
2+
# from elastic_transport import RequestsHttpNode ## UNMARK IF RUNING BEHIND PROXY
3+
# from datetime import datetime, timedelta, timezone ## UNMARK TO USE CUSTOM TIME
4+
5+
## TIMEFRAME 2D /7D /30D
6+
'''Uncomment this if U want to change the search timeframe
7+
Once in use, must change the <gte> value in query_string var below'''
8+
# current_time = datetime.now(timezone.utc)
9+
# start_time = current_time - timedelta(days=3)
10+
# fcurrent_time = current_time.strftime('%Y-%m-%dT%H:%M:%S')
11+
# fstart_time = start_time.strftime('%Y-%m-%dT%H:%M:%S')
12+
13+
# PROXIES (IF NEEDED)
14+
proxies = {
15+
'http_proxy': '',
16+
'https_proxy': ''
17+
}
18+
19+
## CONSTRUCT DSL QUERY TO CHECK FOR RESULTS IN LAST ONE WEEK
20+
def eql_query(esurl, es_key, rule_kuery, rule_index):
21+
'''
22+
This function get elastic url, elastic token, query search, and index.
23+
It return the number of results (if so) matched in the past week.
24+
Note! Configure a class CustomHttpNode(RequestsHttpNode) if needed to run behind proxy
25+
'''
26+
es = Elasticsearch(
27+
esurl,
28+
api_key=es_key,
29+
# node_class=CustomHttpNode ## use this if using proxy
30+
)
31+
32+
query_string = {
33+
"query": {
34+
"bool": {
35+
"must": [
36+
{
37+
"query_string": {
38+
"query": f"{rule_kuery}"
39+
}
40+
},
41+
{
42+
"range": {
43+
"@timestamp": {
44+
"gte": "now-1w/w", ## here you can adjust the time as needed. defult I set to 1week.
45+
"lt": "now"
46+
}
47+
}
48+
}
49+
]
50+
}
51+
}
52+
}
53+
54+
try:
55+
response = es.search(index=rule_index, body=query_string)
56+
'''
57+
Using the search method from elasticsearch library.
58+
Uncomment next 3 line if result data is needed
59+
For hit in response['hits']['hits']:
60+
print(hit['_source'])
61+
num_results = response._body['hits']['total']['value']'''
62+
63+
num_results = response._body['hits']['total']['value']
64+
65+
except Exception as e:
66+
print(f"[X] Error executing EQL query: {e}")
67+
68+
return num_results
69+
70+
71+
def check_main(filename, rule_kuery, rule_index):
72+
'''This function is a child one of check_query_main.py.
73+
Receives:
74+
- filename = json file name
75+
- rule_kuery = search query
76+
- rule_index = index to search in
77+
'''
78+
filename = filename
79+
80+
'''get your elk creds from anywhere you saved them.
81+
Make sure to retreive them securely - do not save them hardcoded here!!!'''
82+
esurl = ''
83+
es_key = ''
84+
85+
## TRIGGER eql_query FUNCTION
86+
results = eql_query(esurl, es_key, rule_kuery, rule_index)
87+
88+
## PRINT RESULTS
89+
print(f"Provided query resulted with {results} results")

0 commit comments

Comments
 (0)