#!/bin/python3
#Author:cuijianzhe
from elasticsearch import Elasticsearch
from datetime import datetime, timedelta
#paradigm+
import requests
import json
import sys
import os
def search(es_object, index_name, search):
res = es_object.search(index=index_name, body=search)
for hit in res['hits']['hits']:
# print(hit)
timestamp = hit["_source"]["@timestamp"]
local_time = str(datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ') + timedelta(hours=8))
host = hit["_source"]["host"]
message = hit["_source"]["message"]
# log = {
# "message": hit["_source"]["message"],
# "host": hit["_source"]["host"],
# "timestamp": local_time
# }
# print(log)
result = send_messag(local_time,host,message)
def send_messag(timestamp,host,message):
headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = "https://www.qingzhouim.com/api/msg/groupmsgsend?access_token=d9929741d87d94a9bb0b2940a9a7f12"
body = """
**IPMI登录提醒:**
*服务器IPMI:{}被登录!*
*登录时间: {}*
*设备IP: {}*
**message:** {}
""".format(host,timestamp,host,message)
json_text = {
"message":{
"header":{
"toid":[162531]
},
"body":[
{
"type": "MD",
"content": body
},
]
}
}
response = requests.post(api_url,json=json_text,headers=headers)
print(response.content)
es = Elasticsearch(['http://172.27.128.219:9200'], http_auth=('elastic', 'GuxiqgSIWKffKCHHdP'))
# 获取1小时前的时间
time_one_hour_ago = datetime.now() - timedelta(hours=9)
search_object = {
"query": {
"bool": {
"must": [
{ "match": { "message": "login" } },
{ "range": { "@timestamp": { "gte": time_one_hour_ago }}}
]
}
}
}
search(es, 'gpu-outband*', search_object)
效果:
curl -u 用户名:密码 -H'Content-Type:application/json' -d'{
"query": {
"range": {
"@timestamp": {
"lt": "now-7d",
"format": "epoch_millis"
}
}
}
}
' -XPOST "http://127.0.0.1:9200/*-*/_delete_by_query?pretty"
解释
-u 是格式为 userName:password,使用 Basic Auth 进行登录。如果 Elasticsearch 没有使用类似 x-pack 进行安全登录,则不需要加-u 参数
-H 是指定文档类型是 JSON 格式
-XPOST 是指定用 POST 方式请求
-d 是指定 body 内容