[Python] Read and Extract details from Log file

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    My log file contains details as shown below:

    • Message[Success] Thu Mar 02 08:03:29 2025 License Comsol checked out by machine SBC135.amat.net user Zhangl. Message Thu Mar 02 08:03:35 2025 License Comsol returned by machine SBC139.amat.net.
      Message[Success] Thu Mar 02 08:03:50 2025 License Comsol checked out by machine KLBG213.amat.net user boser. Message Thu Mar 02 08:03:52 2025 License Comsol returned by machine KLBG213.amat.net.
      Message[Success] Thu Mar 02 08:03:58 2025 License Comsol checked out by machine PUN787.amat.net user mehak. Message Thu Mar 02 08:04:04
      2025 License Comsol returned by machine PUN787.amat.net.

    Below code is not working without any output

    My code is :

    import re
    log_file_path = 'C:\\Users\\kkk.txt'
    def extract_user_and_machine(log_file_path):
    # Regular expression to match 'user <username> by machine <machine>'
    pattern = r'user (\S+) by machine (\S+)'

    with open(log_file_path, 'r') as log_file:
    log_lines = log_file.readlines()

    # List to hold extracted 'user@machine' combinations
    user_machine_combinations = []

    for line in log_lines:
    # Search for the pattern in each line
    match = re.search(pattern, line)
    if match:
    # Extract username and machine, then combine them in 'user@machine' format
    username = match.group(1)
    machine = match.group(2)
    user_machine_combinations.append(f"{username}@{machine}")

    # Display the results
    if user_machine_combinations:
    print("User@Machine combinations found in the log file:")
    for combination in user_machine_combinations:
    print(combination)
    else:
    print("No user-machine combinations found in the log file.")

    Continue reading...

Compartilhe esta Página