Search Log File By Python 2.7

นึกถึง Python 2.7 ทุกคนคงอุทานเหมือนกัน ยังมีคนใช้อยู่เหรอเนี่ย.. คือสภาพแวดล้อมเก่าบีบบังคับ เข้าเรื่องกัน ทุกวั้นถ้าเกิดปัญหาหลายๆคนคงนึกถึง log เป็นอันดับแรก แล้วถ้า log มันมหาศาลละ เกิดทีหากันทั้งวัน ปััญหาเหล่านี้จะหมดไป ผมลองเขียนสคิปเพื่อไปหา message ใน log และส่งเมล์ออกมาจากระบบให้ด้วย ไม่ต้องไปเสียเวลา แค่รู้ว่า message จะหาคืออไร เช่นชื่อลูกค้า ช่วงวันเวลา


import os
from datetime import datetime, timedelta
import shutil
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email import encoders
from os.path import basename


class smtp_setting():
    smtp_domain = '192.168.1.1'
    port = 25


def format_date_input(date_input):
    if len(date_input) == 8:
        return "{}-{}-{}".format(date_input[:2], date_input[2:4], date_input[4:])
    else:
        return None


def generate_date_folders(directory, end_date_str):
    end_date = datetime.strptime(end_date_str, "%d%m%Y")
    today = datetime.now()
    while end_date <= today:
        date_folder = os.path.join(directory, end_date.strftime("%Y%m%d"))
        if os.path.exists(date_folder):
            yield date_folder
        end_date += timedelta(days=1)


def send_email(file_path, search_term):
    smtp = smtp_setting()
    sender_email = "[email protected]"
    receiver_email = "[email protected]"
    subject = "Log File Search Term {}".format(search_term)
    body = "Please find the attachment."


    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = subject
    message.attach(MIMEText(body, "plain"))


    with open(file_path, "rb") as attachment:
        part = MIMEApplication(
            attachment.read(),
            Name=basename(file_path)
        )
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(file_path)
    message.attach(part)
    text = message.as_string()


    server = smtplib.SMTP(smtp.smtp_domain, smtp.port)
    server.sendmail(sender_email, receiver_email, text)
    print("Email sent to {}".format(receiver_email))
    server.quit()


def search_text_in_files(directory, search_term, end_date_str):
    formatted_end_date_str = format_date_input(end_date_str)
    if not formatted_end_date_str:
        print("Invalid date format. Please enter the date in DDMMYYYY format.")
        return


    destination_path = '/home/m1n/log-tmp/'
    if not os.path.exists(destination_path):
        os.makedirs(destination_path)
    
    matches_found = 0
    for date_directory in generate_date_folders(directory, end_date_str):
        for filename in os.listdir(date_directory):
            if filename.endswith('.log'):
                file_path = os.path.join(date_directory, filename)
                try:
                    with open(file_path, 'r') as file:
                        lines = file.readlines()
                        for line_number, line in enumerate(lines, 1):
                            if search_term in line:
                                print('Found "{}" in {} line {}'.format(search_term, filename, line_number))
                                matches_found += 1
                                destination_file_path = os.path.join(destination_path, filename)
                                if not os.path.exists(destination_file_path):
                                    shutil.copy(file_path, destination_path)
                                    print('Copied "{}" to {}'.format(filename, destination_path))
                                    send_email(destination_file_path, search_term)  
                                else:
                                    print('File {} already exists in destination. Not copied.'.format(filename))
                except IOError:
                    print('File not found: {}'.format(file_path))
    if matches_found == 0:
        print('No matches found for "{}" in the specified date range.'.format(search_term))


if __name__ == "__main__":
    path_mapping = {
        '1': 'AServiceLog',
        '2': 'BServiceLog',
        '3': 'CServiceLog',
        '4': 'DServiceLog',
        '5': 'EServiceLog',
        '6': 'FServiceLog',
        '7': 'GServiceLog',
        '8': 'HServiceLog',
        '9': 'IServiceLog',
    }
    print("= PATH ===================")
    for key in sorted(path_mapping.keys(), key=int):
        print("{} > /data/{}".format(key, path_mapping[key]))
    print("=========================")
    path_number = raw_input("Enter Path Number: ")
    directory = '/data/' + path_mapping.get(path_number)
    if not directory:
        print("Invalid Path Number.")
    else:
        search_term = raw_input("Enter the search term: ")
        end_date_input = raw_input("Enter the end date for search (DDMMYYYY): ")
        search_text_in_files(directory, search_term, end_date_input)



หวังว่าคงช่วยแก้ปัญหา ที่กำลังหาอยู่ได้นะครับ

0
46