2nd FIle
unknown
plain_text
2 years ago
2.4 kB
5
Indexable
import requests import json from email.mime.text import MIMEText import smtplib import csv from datetime import datetime from datetime import datetime from dateutil import tz import pytz # Elasticsearch host and port es_host = "10.206.77.85" es_port = "9200" # Elasticsearch index pattern index_pattern = "metricbeat-" # Elasticsearch _cat/indices API endpoint api_endpoint = f"http://{es_host}:{es_port}/_cat/indices?format=json&pretty" # Send HTTP GET request to the API endpoint response = requests.get(api_endpoint) # Parse JSON response indices = json.loads(response.content) # Filter indices by name pattern filtered_indices = [i['index'] for i in indices if i['index'].startswith(index_pattern)] print(filtered_indices) # # Sort indices by creation date (latest first) sorted_indices = sorted(filtered_indices, reverse=True) a = sorted_indices[0] print(sorted_indices) url = f"http://{es_host}:{es_port}/{a}/_search" payload = json.dumps( { "query": { "bool": { "should": [ { "match": { "metricset.name": "cpu" } } ] } } }) headers = { 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data=payload) output = response.json() hits = output['hits']['hits'] #time coverter from UTC to IST def timecovert_UTCtoIST(temp_timestamp): temp_timestamp = datetime.strptime(temp_timestamp, '%Y-%m-%dT%H:%M:%S.%fZ') temp_timestamp = temp_timestamp.replace(tzinfo=pytz.UTC) local_zone = tz.tzlocal() # Convert UTC to local time zone local_dt = temp_timestamp.astimezone(local_zone) return local_dt for hit in hits: source = hit['_source'] hostname = source['host']['hostname'] cpu = source['system']['pct'] timestamp = timecovert_UTCtoIST(source['@timestamp']) if cpu > 0.8: with open(r'C:\Users\kirpa\Downloads\hari.csv', 'a', encoding='UTF8', newline='') as f: # create the csv writer writer = csv.writer(f) row = [hostname, cpu, timestamp] writer.writerow(row) # Closing file f.close()
Editor is loading...