top of page

WMI Services 

import wmi
import csv
# --- Import Custom Mail Module ---
import sys
sys.path.append(r"C:\PYTHON\modules")
import sendmail2

# --- Section A pulls Service Info on Remote Windows System and Exports to CSV File in Same Folder as Script ---
# --- Section B calls the Email Module function with associated paramters and sends CSV file as attachemnt   ---
# --- EMail Module Fucntion: 
# ------ Checks if the file exists
# ------ Checks if File Size Large than 1KB

# ---------- Section (A) Pull WMI Information --- Export to File -------------------
def get_service_info_and_export(remote_host, username, password, output_file):
    try:
        # Connect to the remote machine
        connection = wmi.WMI(
            computer=remote_host,
            user=username,
            password=password
        )

        # Prepare data for CSV
        service_data = []
        for service in connection.Win32_Service():
            service_data.append({
                "Service Name": service.Name,
                "Display Name": service.DisplayName,
                "State": service.State,
                "Start Mode": service.StartMode,
                "Process ID": service.ProcessId,
                "Description": service.Description or "N/A"
            })

        # Write data to a CSV file
        with open(output_file, mode="w", newline="", encoding="utf-8") as csvfile:
            fieldnames = ["Service Name", "Display Name", "State", "Start Mode", "Process ID", "Description"]
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

            # Write header and rows
            writer.writeheader()
            writer.writerows(service_data)
        print(f"Service information exported successfully to {output_file}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    # >>>> --- Execute WMI Section | Update As Needed --- <<<<<<
    remote_host = "Blacky"  # Replace with the remote machine's hostname or IP
    username = "XXXXXX"  # Replace with a username with permissions to access the remote machine
    password = "XXXXXX"  # Replace with the user's password
    output_file = "service_info.csv"  # Replace with your desired output file path
    get_service_info_and_export(remote_host, username, password, output_file)
    
    # ------------------ Section (B) Execute Email Module Function ------------
    # --- Update as Needed ---

    to = "shead@scriptsbyscott.com"
    server = "Script Message From Server: WINSQL19"
    # --- Path to Attachment ---
    filepathandname = r"C:/PYTHON/Scripts/service_info.csv"
    subject = "Windows Services with Attached Email"
    filename = "service_info.csv"

    # --- Call the email function ---
    sendmail2.email(to, server, filepathandname, subject, filename)
 

bottom of page