Thursday, June 11, 2026

How to Build an Automated System Security Audit Tool with Auto-Logging in Python

Manually auditing a Windows machine for security vulnerabilities is tedious, but losing track of historical security data is worse. Leaving unneeded network shares active or firewalls misconfigured creates massive security gaps, and IT admins need permanent records of these vulnerabilities for compliance.

Instead of copying console outputs manually, we can update our Python automation tool to instantly audit critical operating system configurations and automatically dump the results into a clean, structured text log file.

Here is the complete HTML code framework and automation script featuring native text file exportation.


🐍 The Python Security Audit Script (with Auto-Logging)

This script requires zero third-party installations. It utilizes native modules like subprocess, ctypes, and the sys module to redirect print statements directly into a local log file. Copy this code into a file named security_audit.py:

import os
import sys
import ctypes
import subprocess
from datetime import datetime

class Logger(object):
    """Custom stream redirector to print to both console and a log file."""
    def __init__(self, filename="security_audit_report.txt"):
        self.terminal = sys.stdout
        self.log = open(filename, "w", encoding="utf-8")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        self.terminal.flush()
        self.log.flush()

def is_admin():
    """Checks if the script is running with administrative privileges."""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def check_firewall_status():
    """Audits the Windows Defender Firewall status across profiles."""
    print("[*] Auditing Windows Firewall Status...")
    try:
        cmd = "netsh advfirewall show allprofiles state"
        result = subprocess.check_output(cmd, shell=True, text=True)
        if "OFF" in result.upper():
            print("[ALERT] Firewall is turned OFF on one or more profiles!")
        else:
            print("[OK] Firewall profiles are active.")
    except Exception as e:
        print(f"[ERROR] Failed to audit firewall: {e}")

def check_network_shares():
    """Lists all active network shares exposed on the machine."""
    print("\n[*] Auditing Active Network Shares...")
    try:
        result = subprocess.check_output("net share", shell=True, text=True)
        print(result.strip())
    except Exception as e:
        print(f"[ERROR] Failed to fetch network shares: {e}")

def check_password_policy():
    """Checks the local password account requirements."""
    print("\n[*] Auditing Account Password Policies...")
    try:
        result = subprocess.check_output("net accounts", shell=True, text=True)
        print(result.strip())
    except Exception as e:
        print(f"[ERROR] Failed to fetch password policy: {e}")

def run_audit():
    """Executes the complete security audit sequence and logs results."""
    # Redirect stdout to both the console and the log file
    log_filename = "security_audit_report.txt"
    sys.stdout = Logger(log_filename)
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    print("=" * 50)
    print("      AYOULI IT TECH SYSTEM SECURITY AUDIT      ")
    print(f"      Generated On: {timestamp}       ")
    print("=" * 50)
    
    if not is_admin():
        print("[WARNING] Script is not running as Administrator.")
        print("[WARNING] Some deep system metrics may be missing.\n")
    
    check_firewall_status()
    check_network_shares()
    check_password_policy()
    
    print("\n" + "=" * 50)
    print(f"Audit Complete. Results exported to: {os.path.abspath(log_filename)}")
    print("=" * 50)

if __name__ == "__main__":
    run_audit()

⚙️ How to Deploy and Find the Exported Log

1. Run as Administrator

Search for cmd in your Windows Start menu, right-click it, and select Run as administrator to ensure the script has system read access.

2. Run the Script

Navigate to your script folder and launch the file:

python security_audit.py

3. View Your Text Report

The script handles file creation seamlessly. Look inside the exact same folder where your python script lives. You will find a new file named security_audit_report.txt containing the full text output for your records.

No comments:

Post a Comment