之前发布的一篇博文 "ES中获取AD账号锁定日志" ,在后续的使用中有发送重复消息的问题,因此对脚本进行了进一步优化。


  • 优化后的脚本
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#author: shizhenning 20240828
from elasticsearch import Elasticsearch
import json
from datetime import datetime,timedelta
import requests
import time
import os
from collections import Counter

end_date = datetime.now() - timedelta(minutes=480)
start_date = end_date - timedelta(minutes=5)
date = datetime.now().date().strftime('%Y.%m.%d')
index = "windowsserver-eventlog-%s"%(date)
host = 'http://elasticsearch.example.com:10086'
es = Elasticsearch(host, http_auth=('account', 'password'), request_timeout=100,encodings='utf-8')

### 获取event id 4740;

def get_event4740():
    query = {
        'query': {
            'bool':{
                'must':[
                    {'range':{
                        '@timestamp':{
                            'gte':start_date,
                            'lte':end_date,
                            }
                        }
                     },
                    {'term':{
                            'winlog.event_id':'4740'
                            }
                        },
                    ]
                }
            }
        }
    items = es.search(index=index, body=query)
    datas =items['hits']['hits']
    return datas

### 钉钉消息;

webhook = "https://api.dingtalk.com/robot/send?access_token=1234567890"    
headers = {'content-type': 'application/json'}
timestamp = str(round(time.time() * 1000))
          
def sendMsg(username,locktime,name,body,*args):
    singleURL = ''
    url = '{0}& timestamp={1}'.format(webhook, timestamp)
    values = {
        "msgtype": "actionCard",
        "actionCard": {
            "title": "IT账号锁定通知",
            "text":
               f'### **被锁定别名:{username}**\n'
               f'**锁定时间:{locktime}**\n\n'
               f'**名称:{name}**\n\n'
               f'**最近10分钟登录失败信息:**\n\n'
               f'**{body}**\n\n',
            "singleURL": singleURL
            }
        }
    data = json.dumps(values)
    response = requests.post(url, headers=headers, data=data)
    print(response.text)

### 根据TargetUsername进一步获取event id 4625;
datas = get_event4740()
lock_user_list = [] #定义列表,发送过消息的加入列表
for i in datas:
    info = i['_source']
#   print(json.dumps(info,ensure_ascii=False,indent=4))
    username = info['winlog']['event_data']['TargetUserName']
    locktime_utcstr = info['@timestamp'].replace('T',' ').replace('Z','')   
    locktime_utc = datetime.strptime(locktime_utcstr, '%Y-%m-%d %H:%M:%S.%f') 
    locktime = locktime_utc + timedelta(hours=8)
    locktime = locktime.strftime('%Y-%m-%d %H:%M:%S')
    #####
    print(lock_user_list)
    if username not in lock_user_list:
        name = os.popen("powershell.exe (Get-ADUser -Filter {samaccountname -eq '%s'}).name" %username)
        name = name.read().rstrip()
        start_date1 = locktime_utc - timedelta(minutes=10)
        end_date1 = locktime_utc
        query2 = {
            'query': {
                'bool':{
                    'must':[
                        {'range':{
                            '@timestamp':{
                                'gte':start_date1,
                                'lte':end_date1,
                                }
                            }
                        },
                        {'term':{
                            'winlog.event_id':'4625'
                            }
                        },
                        {'term':{
                            'winlog.event_data.TargetUserName':username
                            }
                        },
                        ]
                    }
                }
            }
        items2 = es.search(index=index, body=query2)
        datas2 =items2['hits']['hits']
        bodylist = []
        for j in datas2:
            info2 = j['_source']
#            print(json.dumps(info2,ensure_ascii=False,indent=4))
            ip_data = info2['winlog']['event_data']['IpAddress']
            server = info2['winlog']['computer_name']
            workstation = info2['winlog']['event_data']['WorkstationName']
            
            bodyitem = "IP:" + ip_data  + ',' + "Station:" + workstation  + ',' + "Server: " + server
            bodylist.append(bodyitem)
            bodyinfo = dict(Counter(bodylist))

            bodys = ""
            for k,v in bodyinfo.items():
                bodys = bodys + k + '[' + str(v) +']' + '; '
         #  print(bodys)
        sendMsg(username,locktime,name,bodys)
        lock_user_list.append(username)
    print(lock_user_list)